There are two problems and an issue with that code:
getElementsByTagName
returns a collection of elements, not just a single element. More here.
There's nothing that attaches the function color
to an element or collection of elements.
To use this
as the element, you'll need to make sure color
is called in a special way.
Also note there's no need for the return
in color
.
If you want to apply the color
function to all matching elements, you'll need a loop:
function color(property) {
this.style.color = property;
}
var list = document.getElementsByTagName("div");
for (var i = 0; i < list.length; ++i) {
color.call(list[i], "red");
}
<div> text text </div>
But if you don't use this
, the call is clearer:
function color(el, property) {
el.style.color = property;
}
var list = document.getElementsByTagName("div");
for (var i = 0; i < list.length; ++i) {
color(list[i], "red");
}
<div> text text </div>
Note: You could add a property to the HTMLElement
prototype (or even NodeList
or HTMLCollection
) so you could call color
as a method, as you did in your question. That's probably not a good idea; if everyone did it, it would quickly lead to conflicts. Generally it's better to only modify the built-in DOM prototypes when applying a polyfill, but not for custom functions.