Reputation: 369
There is a code I'm working on - https://jsfiddle.net/md_bender/pj6a1akz/3/. I need to create new elements and append them to the existing element ul. With creating elements and appending everything is OK. But I don't know how to create child element in the created element. I need to create
<img src="path"/>
In the div I have created earlier in script. It must be like that
<div class="img-w js-popup">
<img src="path"/>
</div>
<a href="delete.php">Delete</a>
But only I can do is create as next sibling to the div
<div class="img-w js-popup"></div>
<img src="path"/>
<a href="delete.php">Delete</a>
Who can help me and solve my problem?
Upvotes: 3
Views: 289
Reputation: 978
$('<li/>')
.append($('<div/>', {
'class': 'img-w js-popup',
}))
.append($('<div/>', {
'id': 'idOFDiv'
}))
.append($('<a/>', {
href: 'delete.php',
text: 'Delete'
}))
.appendTo('ul');
$("#idOFDiv").append($('<img/>', {
'src': '//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80'
}));
Upvotes: 0
Reputation: 122145
You can append img
to div
before you append that div to li
. You can also write the same code like this Fiddle
$('<li/>')
.append($('<div/>', {
'class': 'img-w js-popup',
}).append($('<img/>', {
'src': '//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80'
})))
.append($('<a/>', {
href: 'delete.php',
text: 'Delete'
}))
.appendTo('ul');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<div>
<img src="//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80" alt="" />
</div>
<a href="delete.php">Delete</a>
</li>
</ul>
Upvotes: 2
Reputation:
If do not need single DOMs (li, div, img) its easier to create static string and append whole into list, just like that (remember about backslashes):
$('ul').append("<li><div><img src=\"//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80\" alt=\"\"/></div><a href=\"delete.php\">Delete</a></li>");
Upvotes: 0
Reputation: 337713
The issue is because your append()
call is on the li
itself, not the div
you just added. Try this:
var $div = $('<div/>', {
'class': 'img-w js-popup'
});
$('<img/>', {
'src': '//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80'
}).appendTo($div)
$('<li/>').append($div).append($('<a/>', {
href: 'delete.php',
text: 'Delete'
})).appendTo('ul');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ul>
<li>
<div>
<img src="//www.gravatar.com/avatar/9142888a2ae6160f2faec90134eeafa3/?default=&s=80" alt="" />
</div>
<a href="delete.php">Delete</a>
</li>
</ul>
With that said, you're using the most verbose method of creating HTML. As you're hard-coding all attributes, it can be simplified by just providing the plain string - or even by just cloning the previous li
and appending that.
Upvotes: 0