Dive Into Greasemonkey

Teaching an old web new tricks

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);
}

Real examples

← Doing something for every element with a certain attribute
Inserting content after an element →