Reputation: 3209
I have this code here:
$(".entry-content h2").each(function( index ) {
$(this).wrap('<li></li>');
});
and this wraps opening and closing li tags around each h2 tag...how would I add the opening ul tag at the start and the closing ul tag at the end?
Upvotes: 1
Views: 76
Reputation: 82
try running this BEFORE wrapping the li tags:
$(".entry-content h2").each(function(index){
if (index == 0)
{
$(this).prepend('<ul>');
}
else if(index == $("e.entry-content h2").length - 1)
{
$(this).append('</ul>');
}
})
Upvotes: 0
Reputation: 29188
Here's one method, using closest()
to find the parent container and then wrapInner()
to wrap the container's contents in a <ul>
:
$(".entry-content h2").each(function (index) {
$(this).wrap('<li />');
}).closest('.entry-content').wrapInner('<ul />');
And another method, using parent()
and wrapAll()
:
$(".entry-content h2").each(function (index) {
$(this).wrap('<li></li>');
}).parent().wrapAll('<ul></ul>');
Upvotes: 1
Reputation: 22425
You just have to append the li
into the ul
.
var ul_element = $("<ul></ul>"); //since I don't know your markup
$(".entry-content h2").each(function( index ) {
ul_element.append($(this).wrap('<li></li>'));
}).appendTo("whatever");
Upvotes: 0