最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

dom - Target all links within div — Javascript - Stack Overflow

programmeradmin4浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论