maxum
maxum

Reputation: 2915

Insert new li element after id

Is it possible to add an element after a specific element with an id

 <ul>
      <li>fred</li> 
      <li>wilma</li>
      <li id ="name">barny</li>
      <li> </li>
      <li> </li>
 </ul>

Insert betty after barny by specifying the id name

Upvotes: 0

Views: 2105

Answers (2)

AntonyManoj
AntonyManoj

Reputation: 157

Hope it helps

<!DOCTYPE html>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
    <html>
    <head>
    <script>
    function test()
    {

    $("#name").after("<li id='loremId' name='lorem' >lorem</li>")
    $("#loremId").after("<li id='ipsumId' name='ipsum' >ipsum</li>")
    }
    </script>
    </head>
    <body>
     <ul>
          <li>fred</li> 
          <li>wilma</li>
          <li id ="name">barny</li>
     </ul>



    <script>
    test();
    </script>
    </body>
    </html> 

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074335

Sure, just find that element via document.getElementById, create the new element via document.createElement, and then (this is the tricky bit) insert it by calling Element#insertBefore on the parentNode of the one you want to insert after, specifying you reference element's nextSibling as the reference node.

E.g.:

var elm = document.getElementById("name");
var newElm = document.createElement("li");
newElm.innerHTML = "You probably want something here";
elm.parentNode.insertBefore(newElm, elm.nextSibling);

Note that this even works if your reference node is the last node in its parent. In that case, nextSibling will be null, and insertBefore knows what to do with that.

Upvotes: 2

Related Questions