本文介绍了定位div中的所有链接 - Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定位某个div的链接。我知道如何定位所有链接,如下所示:

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/

有没有办法让我去定位某个id / class中的所有链接?

Is there a way for me to target all the links within a certain id/class?

推荐答案

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();
    }
}

基本上你遵循相同的概念,链接。唯一的区别是你不要用文档作为参考。首先你抓住你想要的div,然后从那里抓住所有锚标签的数组。

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中的所有链接 - Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 05:58