定位 div 中的所有链接——Javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15765639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Target all links within div — Javascript
提问by Jeff Shaver
I'm trying to target links within a certain div. I understand how to target all the links, like so:
我正在尝试定位某个 div 中的链接。我了解如何定位所有链接,如下所示:
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/
显然,它针对所有链接:http: //lexicantest.tumblr.com/
Is there a way for me to target all the links within a certain id/class?
有没有办法让我定位某个 ID/类中的所有链接?
回答by Jeff Shaver
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.
基本上,您遵循与获取所有链接相同的概念。唯一的区别是您不使用该文档作为参考。首先获取所需的 div,然后从那里获取所有锚标记的数组。