jQuery - Adding elements outside existing elements

jQuery

In this tutorial we will learn to manipulate DOM by adding new elements outside existing elements using jQuery.

We can use the following methods to add new elements outside existing elements.

  • before()
  • insertBefore()
  • after()
  • insertAfter()

before()

We use the before() method to add an element before any given element.

In the following example we are adding a paragraph before a div having id "sample-div1".

HTML

<div id="sample-div1">
  <p>Para 1</p>
  <p>Para 2</p>
  <p>Para 3</p>
</div>

jQuery

$("#sample-div1").before("<p>Para 4</p>");

Output

<p>Para 4</p>
<div id="sample-div1">
  <p>Para 1</p>
  <p>Para 2</p>
  <p>Para 3</p>
</div>

insertBefore()

This is similar to before() method and only differs in the way we write the code to add new element before a given element.

We are considering the same above example and adding a new paragraph before a div having id "sample-div1".

$("<p>Para 4</p>").insertBefore("#sample-div1");

after()

We use the after() method to add an element after any given element.

In the following example we are adding a paragraph after a div having id "sample-div1".

HTML

<div id="sample-div1">
  <p>Para 1</p>
  <p>Para 2</p>
  <p>Para 3</p>
</div>

jQuery

$("#sample-div1").after("<p>Para 4</p>");

Output

<div id="sample-div1">
  <p>Para 1</p>
  <p>Para 2</p>
  <p>Para 3</p>
</div>
<p>Para 4</p>

insertAfter()

This is similar to after() method and only differs in the way we write the code to add new element after a given element.

We are considering the same above example and adding a new paragraph after a div having id "sample-div1".

$("<p>Para 4</p>").insertAfter("#sample-div1");