Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append before last child

Tags:

I have a div with the ID wrapper, and I am using .append() to insert some content at the end of that div, like this:

$("#wrapper").append('<div class="content"><div class="subcontent">Some stuff</div></div>'); 

However, I also want the option to insert a new child before the last content div in the wrapper.

So if the HTML output looks like this:

<div id="wrapper">     <div class="content">         <div class="subcontent">             First         </div>     </div>     <div class="content">         <div class="subcontent">             Second         </div>     </div> </div> 

I want to insert an element before the last one, so I get this:

<div id="wrapper">     <div class="content">         <div class="subcontent">             First         </div>     </div>     <div class="content">         <div class="subcontent">             Third         </div>     </div>     <div class="content">         <div class="subcontent">             Second         </div>     </div> </div> 

How would I do this?

like image 878
Boxiom Avatar asked May 06 '15 08:05

Boxiom


People also ask

How do I append my last child?

To insert element as a last child using jQuery, use the append() method. The append( content ) method appends content to the inside of every matched element.

How do you add an element before another element?

In vanilla JavaScript, you can use the insertBefore() method to insert an element before another HTML element in the DOM. This method adds an element, right before an existing element in the document.

How do I append my first child?

To insert element as a first child using jQuery, use the prepend() method. The prepend( content ) method prepends content to the inside of every matched element.

What is insert before?

insertBefore() The insertBefore() method of the Node interface inserts a node before a reference node as a child of a specified parent node. If the given node already exists in the document, insertBefore() moves it from its current position to the new position.


1 Answers

You could use .before() to add a sibling before the element:

$("#wrapper .content:last").before('<div class="content"><div class="subcontent">Third</div></div>'); 

.insertBefore() does the same thing with a different syntax, namely that you select the element to be added, and pass the element you want to add it before.

$("#wrapper .content:last").before('<div class="content"><div class="subcontent">Third</div></div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  <div id="wrapper">      <div class="content">          <div class="subcontent">              First          </div>      </div>      <div class="content">          <div class="subcontent">              Second          </div>      </div>  </div>
like image 156
Scimonster Avatar answered Dec 19 '22 03:12

Scimonster