Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Help using .each() and .append() to add pictures to HTML

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!

like image 205
cydonknight Avatar asked Nov 21 '12 03:11

cydonknight


People also ask

How can add image in HTML using jQuery?

With jQuery, you can dynamically create a new image element and append it at the end of the DOM container using the . append() method.

What is the use of append in jQuery?

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.

What is the difference between append and appendTo in jQuery?

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.


3 Answers

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">');
});
like image 99
site Avatar answered Nov 16 '22 03:11

site


$(".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">');
like image 32
ahren Avatar answered Nov 16 '22 03:11

ahren


Try using this:

$(".faq").each(function(){
    $('.letter-q', this).append('<img src="images/faq-q.png" alt="Question">');
});
like image 27
arulmr Avatar answered Nov 16 '22 01:11

arulmr