I'm trying to target links within a certain div. I understand how to target all the links, like so:
var colors = [ 'BlueViolet', 'CadetBlue', 'Coral', 'Crimson', 'DarkGoldenRod', 'DarkOliveGreen'],
a = document.getElementsByTagName('a');
for(var i = 0; i < a.length; i++) {
var elem = a[i],
color = colors[0];
elem.style.color = color;
colors.push(color);
colors.shift();
}
Obviously, it's targeting all links: /
Is there a way for me to target all the links within a certain id/class?
I'm trying to target links within a certain div. I understand how to target all the links, like so:
var colors = [ 'BlueViolet', 'CadetBlue', 'Coral', 'Crimson', 'DarkGoldenRod', 'DarkOliveGreen'],
a = document.getElementsByTagName('a');
for(var i = 0; i < a.length; i++) {
var elem = a[i],
color = colors[0];
elem.style.color = color;
colors.push(color);
colors.shift();
}
Obviously, it's targeting all links: http://lexicantest.tumblr.com/
Is there a way for me to target all the links within a certain id/class?
Share Improve this question asked Apr 2, 2013 at 13:39 user1469270user1469270 2- Is it acceptable to use jquery? – Aaron Kurtzhals Commented Apr 2, 2013 at 13:40
- If it's possible to translate the loop I've used above, then it would be preferable :) – user1469270 Commented Apr 2, 2013 at 13:51
1 Answer
Reset to default 19For ID:
var a = document.getElementById('divYouwant').getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
var elem = a[i],
color = colors[0];
elem.style.color = color;
colors.push(color);
colors.shift();
}
If you want to grab it from a class, you would have to grab each class and then grab each set of anchor tags...
var divs = document.getElementsByClassName('className');
for (var i = 0; i < divs.length; i++) {
var a = divs[i].getElementsByTagName('a');
for (var j = 0; j < a.length; j++) {
var elem = a[j],
color = colors[0];
elem.style.color = color;
colors.push(color);
colors.shift();
}
}
Basically you follow the same concept as just getting all the links. The only difference is you don't use the document as the reference. First you grab the div that you want, and then from there, grab an array of all the anchor tags.