Dive Into Greasemonkey

Teaching an old web new tricks

4.10. Replacing an element with new content

Once you find an element, you can replace it with entirely new content, using the replaceChild function.

Example: Replace an image with its alt text

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

var theImage, altText;
theImage = document.getElementById('annoyingsmily');
if (theImage) {
    altText = document.createTextNode(theImage.alt);
    theImage.parentNode.replaceChild(altText, theImage);
}
[Note]

If you want to replace an element with a large chunk of HTML, you can construct the HTML as a string and then set the element's innerHTML property.

Real examples

← Removing an element
Inserting complex HTML quickly →