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!
You don't need the outer
.each()
call at all. Just the inner line should do what you want:Your code is doing the equivalent of "for each .faq (of which there are five), find all .faq .letter-q on the page and add an image". All you really need is the last clause of that sentence.
Try using this:
Add a
context
to your selectorRead more: http://api.jquery.com/jQuery/
Or you can just not use a loop...
It's worth noting that there's probably a pure-CSS solution to this problem as well. Rather than inserting
<img>
tags in the page, you could use the source of the image as a background to the target (if it doesn't have a background already).Without knowing the structure of the HTML and other CSS applied, it's impossible to be sure, but here's a guess:
Try this,
If I understood what you need, all you gotta do is run once and not a loop.
I guess that the main problem is that when your doing this loop the result should be like this.
Before loop:
The first time will result:
The second time:
and so on ....
Regards, Eddiedu