Dive Into Greasemonkey

Teaching an old web new tricks

4.8. Inserting content after an element

Once you've found an element, you may wish to insert additional content after it. You can use the insertBefore function for this too, combined with the nextSibling property.

Example: Insert an <hr> after the navigation bar

This presumes that there is an element whose ID is "navbar".

var navbar, newElement;
navbar = document.getElementById('navbar');
if (navbar) {
    newElement = document.createElement('hr');
    navbar.parentNode.insertBefore(newElement, navbar.nextSibling);
}
[Tip]

Inserting new content before someExistingElement.nextSibling will work even if someExistingElement is the last child of its parent (i.e. it has no next sibling). In this case, someExistingElement.nextSibling will return null, and the insertBefore function will simply append the new content after all other siblings. (If this doesn't make any sense to you, don't worry about it. The point is that this example will always work, even when it seems like it shouldn't.)

← Inserting content before an element
Removing an element →