user1269625
user1269625

Reputation: 3209

JQuery write opening and closing ul tags around a script

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

Answers (3)

AleB
AleB

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

showdev
showdev

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 />');

http://jsfiddle.net/nF6ea/


Edit:

And another method, using parent() and wrapAll():

$(".entry-content h2").each(function (index) {
    $(this).wrap('<li></li>');
}).parent().wrapAll('<ul></ul>');

http://jsfiddle.net/nF6ea/2/

Upvotes: 1

Sterling Archer
Sterling Archer

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

Related Questions