Simple bug that needs to be fixed and I can't figure out what's wrong. I need to append the same picture to multiple (five) divs in the HTML. For some reason, my code is appending the same picture five times to each div. Making it more clear, each of the five divs needs one picture. Right now, all five have five pictures each. Here is the JQUERY:
$(".faq").each(function(){
$('.faq .letter-q').append('<img src="images/faq-q.png" alt="Question">');
});
This is where it is being inserted:
<div class="letter-q"></div>
There are five of those spread out across the body.
It's probably something small I'm missing. Any help would be appreciated!
With jQuery, you can dynamically create a new image element and append it at the end of the DOM container using the . append() method.
jQuery append() Method The append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.
The append (content) method appends content to the inside of every matched element, whereas the appendTo (selector) method appends all of the matched elements to another, specified, set of elements.
If you want to work with the five .letter-q div's first then select them first so that ".each" time the function is run it is working with those div's:
$('.faq .letter-q').each(function(){
//this wrapped in jQuery will give us the current .letter-q div
$(this).append('<img src="images/faq-q.png" alt="Question">');
});
$(".faq").each(function(){
$('.letter-q', this).append('<img src="images/faq-q.png" alt="Question">');
});
Add a context
to your selector
Read more: http://api.jquery.com/jQuery/
Or you can just not use a loop...
$('.faq .letter-q').append('<img src="images/faq-q.png" alt="Question">');
Try using this:
$(".faq").each(function(){
$('.letter-q', this).append('<img src="images/faq-q.png" alt="Question">');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With