1

I want to concatenate the html of images using jquery in each loop. Here is my code which is not working. I am getting url of images from li attributes and then setting image tag for each url. I am able to get the url successfully but can't concatenate the image tags for each li. need assistance

$('.nav li').each(function(){
        var img_link = $(this).attr('data-menu');
        var img_html = '<img src="'+img_link+'">';
        // here I have to concatenate the img_html in gethtml variable and then I will put it in a div.                 
        });
        $('.main-img').html(gethtml);
1

3 Answers 3

4

You need to do gethtml += '<img src="'+img_link+'">'; and initialise gethtml as '' outside the loop:

var gethtml ='';
$('.nav li').each(function(){
    var img_link = $(this).attr('data-menu');
    gethtml += '<img src="'+img_link+'">';
});
$('.main-img').html(gethtml);
Sign up to request clarification or add additional context in comments.

5 Comments

@Rizwi you can tick mark the answer if that was helpful to you
@rizwi you need to initialize the gethtml outside of the loop because of scope. w3schools.com/js/js_scope.asp
@AnkitAgarwal Slow internet got me lacking. :P
@TylerFowle it's outside
@AnkitAgarwal just further explaining why you have to do that
3

Try out this code:

let gethtml = '';
$('.nav li').each(function() {
    var img_link = $(this).attr('data-menu');
    var img_html = '<img src="'+img_link+'">';
    gethtml += img_html + ', ';                
});

$('.main-img').html(gethtml);

It will concatenate the gethtml variable with the img_html separated by commas.

Comments

0

It's better to use append for doing that like below:

$('.nav li').each(function () {        
    $('.main-img').append($(document.createElement('img')).attr("src", $(this).attr('data-menu')));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.