John Zuxer John Zuxer - 6 months ago 8
Javascript Question

jquery create 2 new elements in one variable

Can i create 2 new elements in one variable and then use .html() with this variable?
I know i can just write a string of this element like this

var foo = '<img class="foo" src="/foo1.jpg"><img class="foo" src="/foo2.jpg">';
$('#test').html(foo);


But can i do it with this syntax somehow? (This is not working)

var foo = $('<img>',{
'class': 'foo',
src: '/foo1.jpg'
}), $('<img>',{
'class': 'foo',
src: '/foo2.jpg'
});
$('#test').html(foo);

Answer

Put it inside array

var foo = [$('<img>', {
  'class': 'foo',
  src: '/foo1.jpg'
}), $('<img>', {
  'class': 'foo',
  src: '/foo2.jpg'
})];

$('#test').html(foo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test"></div>

Comments