Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialkhoipro
10,821 PointsJavascript: Add DOM to each element
Hi,
I'm trying to practice using Javascript after finishing a course Jquery Basic and reach an issue.
I have a list below:
<ul class="gallery">
<li>
<img src="http://placehold.it/150x150" alt="Theme 1" />
</li>
<li>
<img src="http://placehold.it/150x150" alt="Theme 2" />
</li>
</ul>
What I want
Javascript should do to get output:
<ul class="gallery">
<li>
<a href="http://placehold.it/150x150"><img src="http://placehold.it/150x150" alt="Theme 1" /></a>
<p class="caption">[alt of image 1]</p>
</li>
<li>
<a href="http://placehold.it/150x150"><img src="http://placehold.it/150x150" alt="Theme 2" /></a>
<p class="caption">[alt of image 2]</p>
</li>
</ul>
I want to create a lighbox for each image, so when click an image it display a lightbox with overlay.
What is my problem?
I can not append to EACH <li></li>. When I tried to append a DOM, it display to ALL elements. So my result is:
<ul class="gallery">
<li>
<a href="http://placehold.it/150x150"><img src="http://placehold.it/150x150" alt="Theme 1" /></a>
<p class="caption">[alt of image 1]</p>
<p class="caption">[alt of image 2]</p>
<p class="caption">[alt of image 3]</p>
</li>
<li>
<a href="http://placehold.it/150x150"><img src="http://placehold.it/150x150" alt="Theme 2" /></a>
<p class="caption">[alt of image 1]</p>
<p class="caption">[alt of image 2]</p>
<p class="caption">[alt of image 3]</p>
</li>
</ul>
How to append a DOM to correct path with repeat action, not a wrong loop like that?
Thank you,
1 Answer
Steven Parker
231,007 PointsYou didn't show any JavaScript code, but it looks like you are setting multiple elements inside a loop.
What you want is to have the loop iterate through the elements, but then inside the loop you want to add only to the one element identified for that iteration.
So, loop through each, but only add to one in the loop.
If that's not enough to get you going, try posting your JavaScript along with your HTML.
Chyno Deluxe
16,936 PointsChyno Deluxe
16,936 PointsCan you provide your code to a site like jsFiddle or CodePen