We can use jQuery to add a sibling to an element by using either the jQuery insertAfter method or the insertBefore method.
$('').insertAfter("#div1");
$('').insertBefore("#div2");
Let’s say I have the following HTML:
This is paragraph 1
This is paragraph 2
This is paragraph 4
If we wanted to add more siblings to the paragraph with class=”p4″ we can use the jQuery insertAfter() and insertBefore() methods to do this with the following jQuery code.
$('This is paragraph 3
').insertBefore(".p4");
$('This is paragraph 5
').insertAfter(".p4");
The result would be as follows:
This is paragraph 1
This is paragraph 2
This is paragraph 3
This is paragraph 4
This is paragraph 5
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery('This is paragraph 3
').insertBefore(".p4");
jQuery('This is paragraph 5
').insertAfter(".p4");
Using jQuery to Add a Sibling to an Element With a Click
In this example, we will have a simple div that will be a box. We will have two buttons to let the user enter a new div box before or after the first div.
Here is our HTML setup
Insert Before
Insert After
In the jquery and JavaScript code, we will have two functions that run when each button is pressed. They will both create a new box with a new color and insert it either before or after the div depending on which button was pressed.
We will also get a random color and assign it to the box in its HTML code. We will then use the insertAfter() or insertBefore method to insert the new box.
Here is the JavaScript code to use jQuery to add a sibling to an element:
//Insert Before
$('#click-me1').click(function(){
//Create a random color
var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
$('').insertBefore("#box1");
});
//Insert After
$('#click-me2').click(function(){
//Create a random color
var randomColor = "#" + (Math.floor(Math.random()*16777215).toString(16));
$('').insertAfter("#box1");
});
The final code and output for this example of how to use jQuery to add a sibling to an element is below:
Code Output:
Full Code:
Insert Before
Insert After
Hopefully this article has helped you understand how to use jQuery to add a sibling to an element.