如何按类名获取子元素? [英] How to get child element by class name?

查看:733
本文介绍了如何按类名获取子元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获得具有class = 4的子跨度。这是一个示例元素:

I'm trying to get the child span that has a class = 4. Here is an example element:

<div id="test">
 <span class="one"></span>
 <span class="two"></span>
 <span class="three"></span>
 <span class="four"></span>
</div>

我可用的工具是JS和YUI2。我可以这样做:

The tools I have available are JS and YUI2. I can do something like this:

doc = document.getElementById('test');
notes = doc.getElementsByClassName('four');

//or

doc = YAHOO.util.Dom.get('#test');
notes = doc.getElementsByClassName('four');

这些在IE中不起作用。我得到一个错误,对象(doc)不支持此方法或属性(getElementsByClassName)。我已经尝试了一些getElementsByClassName的跨浏览器实现的例子但是我无法让它们工作并且仍然有错误。

These do not work in IE. I get an error that the object (doc) doesn't support this method or property (getElementsByClassName). I've tried a few examples of cross browser implementations of getElementsByClassName but I could not get them to work and still got that error.

我认为我需要的是一个十字架浏览器getElementsByClassName或者我需要使用doc.getElementsByTagName('span')并循环直到找到第4类。我不知道怎么做。

I think what I need is a cross browser getElementsByClassName or I need to use doc.getElementsByTagName('span') and loop through until I find class 4. I'm not sure how to do that though.

推荐答案

使用 doc.childNodes 遍历每个 span ,然后过滤 className 等于 4 的那个:

Use doc.childNodes to iterate through each span, and then filter the one whose className equals 4:

var doc = document.getElementById("test");
var notes = null;
for (var i = 0; i < doc.childNodes.length; i++) {
    if (doc.childNodes[i].className == "4") {
      notes = doc.childNodes[i];
      break;
    }        
}

这篇关于如何按类名获取子元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆