Accore LTD
Accore LTD

Reputation: 287

how can insert li by jquery

in wordpress menu create

<a href="#">menu 1</a>
<a href="#">menu 2</a>
<a href="#">menu 3</a>
<a href="#">menu 4</a>
<a href="#">menu 5</a>

but i want to add those are inside li. like this

<li><a href="#">menu 1</a></li>
<li><a href="#">menu 2</a></li>
<li><a href="#">menu 3</a></li>
<li><a href="#">menu 4</a></li>
<li><a href="#">menu 5</a></li>

i know its possible by jquery . i tried but i can't make it. i am not so pro on jquery so would you help for me.

Upvotes: 2

Views: 132

Answers (2)

David Thomas
David Thomas

Reputation: 253506

I'd suggest the following:

var list = $('<ul />').insertBefore($('a').first());

$('a').each(
    function(){
        $(this).wrap('<li />').closest('li').appendTo(list);
    });​

JS Fiddle demo.

Based on my reading of the comments from the OP (below this answer), the problem of the above not working is likely due to the lack of the code being wrapped in a $(document).ready() handler, if that's the case then I'd suggest the following adaptation:

$(document).ready(
    function(){
    var list = $('<ul />').insertBefore($('a').first());

    $('a').each(
        function(){
            $(this).wrap('<li />').closest('li').appendTo(list);
        });​
    });

Upvotes: 3

jeff
jeff

Reputation: 8348

Add classes to the elements you want to put into li elements:

<a href="#" class="li_a">menu 1</a>
<a href="#" class="li_a">menu 2</a>
<a href="#" class="li_a">menu 3</a>
<a href="#" class="li_a">menu 4</a>
<a href="#" class="li_a">menu 5</a>

Then grab those elements and go through them:

var ul = $("<ul></ul>").appendTo("body");
$("a.li_a").each(function() {
    $(this).wrap("<li></li>").parent().appendTo(ul);
});

Upvotes: 0

Related Questions