unable to change colors of a tag

- 1 answer

Ad

i have this code

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="" id="mainLink">Click Me</a>
<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" 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.

Ad

Answer

Ad

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';
});
Ad
source: stackoverflow.com
Ad