Reputation: 117
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);
Upvotes: 1
Views: 9603
Reputation: 9927
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')));
});
Upvotes: 0
Reputation: 158
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.
Upvotes: 3
Reputation: 30739
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);
Upvotes: 4