Reputation: 1514
i have this code
<a href="" id="mainLink">Click Me</a>
<a href="" id="mainLink2">Click Me 2</a>
And then the Js
var mainLinker = document.getElementsByTagName('a');
for (var i = 0; i < mainLinker.length; i++) {
this.style.color = 'red';
}
But i get this error
Cannot set property 'color' of undefined
Please tell me where am i doing it wrong.
Upvotes: 0
Views: 103
Reputation:
Of course your basic problem is using this
, as pointed out in other answers. But why are you doing this instead of using a CSS rule such as
a { color: red; }
If you want to make this conditional somehow, then add a class at a higher level, such as body
, to control it:
body.make-links-red a { color: red }
Then, when you want to make links red, do
document.body.classList.add('make-links-red')
Upvotes: 0
Reputation: 8402
You refer to this
in an object
Your function is not in an object
This will work
var mainLinker = document.getElementsByTagName('a');
for (var i = 0; i < mainLinker.length; i++) {
mainLinker[i].style.color = 'red';
}
Upvotes: 0
Reputation: 451
this
is not what you want.
Change the loop body to
mainLinker[i].style.color = 'red';
or equivalently use forEach
(edited with @Vohuman's comment):
[].forEach.call(document.getElementsByTagName('a'), function(el) {
el.style.color = 'red';
});
Upvotes: 1