HTML DOM API – Custom: insertBefore() Function
The insertBefore() function is a custom function in the HTML DOM API that allows you to insert a new element before a specified node in the DOM tree.
Using this function in Vanilla JavaScript, React.js, or any other web development framework, you can easily manipulate the DOM structure of your web page.
Vanilla JavaScript Example:
// Create a new element
var newElement = document.createElement('div');
newElement.innerHTML = 'This is a new div element';
// Get the parent node
var parentNode = document.getElementById('parent');
// Get the reference node
var referenceNode = document.getElementById('reference');
// Insert the new element before the reference node
parentNode.insertBefore(newElement, referenceNode);
React.js Example:
// Functional component
function MyComponent() {
const parentNodeRef = useRef();
const referenceNodeRef = useRef();
useEffect(() => {
// Create a new element
const newElement = document.createElement('div');
newElement.innerHTML = 'This is a new div element';
// Insert the new element before the reference node
parentNodeRef.current.insertBefore(newElement, referenceNodeRef.current);
}, []);
return (
This is the reference node
);
}
With the insertBefore() function, you can easily customize the position of new elements in the DOM, making your web development tasks more efficient and flexible.