Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How To Add An HTML Element Starting After One And Finishing Before Another One?
This article shows how to add an HTML element in between two existing elements using JavaScript. This is a common task when creating webpages, and can be achieved using the DOM manipulation methods. We will be using the JavaScript API to access and manipulate the elements on our webpage.
The task we are going to perform in this article is adding an HTML element, starting after one and finishing before another one. For this, we are going to use the insertBefore() method along with other DOM manipulation techniques.
Syntax
Following is the syntax for the insertBefore() method
parentNode.insertBefore(newNode, referenceNode)
Where
- parentNode The parent element where the new node will be inserted
- newNode The element to be inserted
- referenceNode The existing element before which the new element will be inserted
Using insertBefore() Method
The Node interface's insertBefore() method places a node as a child of a given parent node ahead of a reference node. The insertBefore() method transfers the specified node to the new place if it already exists in the document.
This method is particularly useful when you need precise control over where an element should be positioned within the DOM tree.
Example Basic Element Insertion
In the following example, we are adding a list item between two existing list items using the insertBefore() method
<!DOCTYPE html>
<html>
<head>
<title>Insert Element Using insertBefore</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Vehicle List</h2>
<ol id="vehicleList">
<li>RX100</li>
<li>DUCATI</li>
</ol>
<script>
// Create new list item
const newItem = document.createElement("li");
const textNode = document.createTextNode("CARS");
newItem.appendChild(textNode);
// Get the list and insert before the second item
const list = document.getElementById("vehicleList");
list.insertBefore(newItem, list.children[1]);
</script>
</body>
</html>
The output displays the list with "CARS" inserted between "RX100" and "DUCATI"
Vehicle List 1. RX100 2. CARS 3. DUCATI
Example Interactive Element Insertion
Execute the following example to see how we can add HTML elements dynamically using a button click
<!DOCTYPE html>
<html>
<head>
<title>Interactive Element Insertion</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Click the button to insert an element before "Monkey"</h2>
<ul id="animalList">
<li>Monkey</li>
<li>Donkey</li>
</ul>
<button onclick="insertElement()" style="padding: 8px 16px; margin-top: 10px;">Insert Element</button>
<script>
function insertElement() {
// Create new list item
var newItem = document.createElement("li");
var textContent = document.createTextNode("Pigeon");
newItem.appendChild(textContent);
// Get the list and insert before the first child
var list = document.getElementById("animalList");
list.insertBefore(newItem, list.firstElementChild);
}
</script>
</body>
</html>
When the script gets executed, it displays a list with a button. Clicking the "Insert Element" button adds "Pigeon" before "Monkey" in the list
Before click: ? Monkey ? Donkey After click: ? Pigeon ? Monkey ? Donkey
Creating Container Elements
You can also create wrapper elements that encompass content between two existing elements. This is useful for grouping content or applying styles to a section.
Example Wrapping Content Between Elements
The following example demonstrates how to create a container div that wraps content between two horizontal rules
<!DOCTYPE html>
<html>
<head>
<title>Wrapping Content Example</title>
<style>
.content-wrapper {
background-color: #f0f8ff;
padding: 15px;
border: 2px solid #4682b4;
border-radius: 8px;
margin: 10px 0;
}
</style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<hr id="startMarker">
<p>Welcome To TutorialsPoint</p>
<span>The Best E-Learning Platform</span>
<hr id="endMarker">
<script>
const startElement = document.getElementById('startMarker');
let nextElement = startElement.nextSibling;
// Create wrapper div
const wrapperDiv = document.createElement('div');
wrapperDiv.className = 'content-wrapper';
// Insert wrapper after start marker
startElement.parentNode.insertBefore(wrapperDiv, nextElement);
// Move all elements between markers into wrapper
while (nextElement && nextElement.id !== 'endMarker') {
let currentNode = nextElement;
nextElement = nextElement.nextSibling;
// Skip text nodes that are just whitespace
if (currentNode.nodeType === 3 && currentNode.textContent.trim() === '') {
continue;
}
wrapperDiv.appendChild(currentNode);
}
</script>
</body>
</html>
The script creates a styled container that wraps the content between the two horizontal rules, giving it a blue border and light blue background
___________________ [Light blue bordered box containing:] Welcome To TutorialsPoint The Best E-Learning Platform ___________________
Alternative Methods
Besides insertBefore(), there are other methods to position elements
- insertAdjacentElement() Provides more flexible positioning options ('beforebegin', 'afterbegin', 'beforeend', 'afterend')
- appendChild() Adds an element as the last child
- prepend() Adds an element as the first child
Example Using insertAdjacentElement
The insertAdjacentElement() method offers more positioning options
<!DOCTYPE html>
<html>
<head>
<title>insertAdjacentElement Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<div id="container">
<p id="targetParagraph">Target Element</p>
</div>
<button onclick="insertElements()" style="padding: 8px 16px; margin-top: 10px;">Insert Elements</button>
<script>
function insertElements() {
const target = document.getElementById('targetParagraph');
// Create elements
const beforeBegin = document.createElement('p');
beforeBegin.textContent = 'Before Begin';
beforeBegin.style.color = 'red';
const afterEnd = document.createElement('p');
afterEnd.textContent = 'After End';
afterEnd.style.color = 'blue';
// Insert elements
target.insertAdjacentElement('beforebegin', beforeBegin);
target.insertAdjacentElement('afterend', afterEnd);
}
</script>
</body>
</html>
This example demonstrates precise positioning around a target element using insertAdjacentElement()
Before click: Target Element After click: Before Begin (red text) Target Element (black text) After End (blue text)
Conclusion
The insertBefore() method is a powerful tool for precisely positioning HTML elements in the DOM. It allows you to add elements at specific positions relative to existing elements, making it essential for dynamic content manipulation. For more flexible positioning options, consider using insertAdjacentElement() which offers four different insertion positions around any target element.
