1

I have the below code:

HTML

<div class="menu">
  <ul>
    <li>
      <a href="#"> 1 </a>
    </li>
    <li>
      <a href="#"> 2 </a>
   </li>
   <li>
    <a href="#"> 3 </a>
   </li>
 </ul>
</div>

and i am trying to add after 1st </li> the code <li><a href="#">More</a><ul> and after the last </li> the closing </ul></li> with Jquery.

I have tried

$( '.menu > ul > li:eq(0)' ).after( '<li><a href="#">More</a><ul>' ); ->tag1
$( '.menu > ul > li:eq(2)' ).after( '</ul></li>' ); ->tag2

Fiddle here http://jsfiddle.net/B86JW/4/

The problem is that <li> and <ul> is automatically self closing and the same thing for </li></ul>

Expected output

<div class="menu">
  <ul>
    <li>
      <a href="#"> 1 </a>
    </li>
    <li><a href="#">More</a> -> tag 1
      <ul> -> tag 1
        <li>
          <a href="#"> 2 </a>
       </li>
       <li>
        <a href="#"> 3 </a>
       </li>
     </ul>
   </li> -> tag 2
 </ul> -> tag 2
</div>

Jsfiddle http://jsfiddle.net/B86JW/4/

4
  • dom manipulation does not work like a string concatenation Commented Nov 18, 2013 at 11:09
  • @ArunPJohny I see, and how can i do this? I know in Vqmod from Opencart i do search and add and i was thinking is quite the same. Commented Nov 18, 2013 at 11:11
  • what is the target markup you want to have Commented Nov 18, 2013 at 11:13
  • @ArunPJohny I have added the expected output above that i want to have. Commented Nov 18, 2013 at 11:15

3 Answers 3

4

try something like this,FIDDLE

    var new_li = $('<li><a href="#">More</a><ul></ul></li>')
    new_li.find('ul').append($( '.menu > ul > li:gt(0)' ));

    $( '.menu > ul > li:eq(0)' ).after( new_li );
Sign up to request clarification or add additional context in comments.

Comments

1

You can try this too:

var html = $('.menu ul li').not(':first').each(function(){
    return this.outerHTML;
});
$( '.menu > ul > li:eq(0)' ).after( '<li><a href="#">More</a><ul></ul></li>' );
$('.menu ul ul').html(html);

Comments

1

Try this,

var xHtml = $( '.menu > ul > li').first().nextAll().detach();
var xNewUl = $("<li><ul></ul></li>").appendTo('.menu > ul');

xNewUl.find('ul').prepend('<a href="#">More</a>').append(xHtml);

DEMO

Updated Version,

var xHtml = $( '.menu > ul > li').first().nextAll().detach();
var xNewUl = $("<li><ul></ul></li>").appendTo('.menu > ul');

xNewUl.prepend('<a href="#">More</a>');
xNewUl.find('ul').append(xHtml);

DEMO I

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.