You are here: Home → Table of contents → Common Patterns → Inserting content before an element
4.7. Inserting content before an element
Once you've found an element (by any means), you may wish to insert additional content before it. You can do this with the
insertBefore
method.
Example: Insert an <hr>
before the main content
This presumes that there is an element whose ID is "main"
.
var main, newElement;
main = document.getElementById('main');
if (main) {
newElement = document.createElement('hr');
main.parentNode.insertBefore(newElement, main);
}