6

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?

2
  • Is it acceptable to use jquery? Commented Apr 2, 2013 at 13:40
  • If it's possible to translate the loop I've used above, then it would be preferable :) Commented Apr 2, 2013 at 13:51

1 Answer 1

19

For 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Just for clarity, this requires that you give the div element and id attribute to be able to reference it.
In the question: links within a certain id/class

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.