Dive Into Greasemonkey

Teaching an old web new tricks

4.11. Inserting complex HTML quickly

The innerHTML property allows you to construct HTML as a string and then insert it directly into the page, without constructing separate DOM objects for each HTML element and setting their attributes one by one.

Example: Insert a banner at the top of the page

var logo = document.createElement("div");
logo.innerHTML = '<div style="margin: 0 auto 0 auto; ' +
    'border-bottom: 1px solid #000000; margin-bottom: 5px; ' +
    'font-size: small; background-color: #000000; ' +
    'color: #ffffff;"><p style="margin: 2px 0 1px 0;"> ' +
    'YOUR TEXT HERE ' +
    '</p></div>';
document.body.insertBefore(logo, document.body.firstChild);

The key here is the second line, where I set logo.innerHTML to a string. Firefox parses the string as HTML and creates all the necessary objects, just like it does for the entire page when it first loads. Then I can insert my new logo (a <div> containing another <div> containing a <p>) into the page at any point — at the beginning of the page, at the end, or before or after any element I choose. In other words, anywhere on the page.

Real examples

← Replacing an element with new content
Adding images without hitting a central server →