Dive Into Greasemonkey

Teaching an old web new tricks

4.5. Doing something for every instance of a specific HTML element

Sometimes you need to do something with every instance of a particular HTML element on a page. For example, you could change the font on every <textarea>. The easiest way to do this is to call getElementsByTagName('tagname'), which returns a collection you can loop through.

Example: Find all the textareas on a page

var allTextareas, thisTextarea;
allTextareas = document.getElementsByTagName('textarea');
for (var i = 0; i < allTextareas.length; i++) {
    thisTextarea = allTextareas[i];
    // do something with thisTextarea
}
[Note]

You should not use this pattern to do something to every link on the page, because the <a> element can also be used for in-page anchors. See Doing something for every element with a certain attribute for how to find all the links on a page.

Real examples

← Doing something for every HTML element
Doing something for every element with a certain attribute →