Thursday, May 26, 2011

Add an element before the last element of it's kind in jQuery wiht insertBefore()


// Add the new tag (li element) before the last tag (li element)
      
$('<li>this is a test 3</li>').insertBefore($('li').last());

In an unordered list such as

<ul>
   <li>this is a test 1</li>
   <li>this is a test 2</li>
   <li>this is a test 4</li>  <------ last element
</ul>

The above jQuery statement will insert it before the last li element -

<ul>
<li>this is a test 1</li>
<li>this is a test 2</li>
<li>this is a test 3</li>  <------ inserted here
<li>this is a test 4</li>  <------ still the last element
</ul>


http://api.jquery.com/insertBefore/