Calling <a> tag from css to javascript function
I am using this changing color script j08691:
function flash() {
var text = document.getElementById('foo');
text.style.color = (text.style.color=='red') ? 'green':'red';
}
var clr = setInterval(flash, 1000);
I want to call a tag <body>and a tag <a>from CSS, not id.
For the tag, <body>I did this and it works:
function flash() {
var text = document.body;
text.style.color = (text.style.color=='black') ? 'white':'black';
}
var clr = setInterval(flash, 1);
But it does not work with the tag <a>. I tried options like:
var els = document.getElementsByTagName('a');
var links = document.getElementsByTagName('a');
Instead of var text = document.getElementById('a');and replacing text.style.colorwith links[i].style.coloror links.style.color, but I'm not quite sure what I'm doing there.
I want to change the colors of all links at once.
+4
2 answers
You are on the right track - it getElementsByTagNamereturns the collection, so just go through the collection:
function flash() {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].style.color = (links[i].style.color=='black') ? 'white':'black';
}
}
setInterval(flash, 1000);
, setInterval , setInterval(x, 1) .
+1