Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

javascript - 如何按类名获取子元素?(How to get child element by class name?)

I'm trying to get the child span that has a class = 4. Here is an example element:(我正在尝试获得具有class = 4的子span。这是一个示例元素:)

<div id="test"> <span class="one"></span> <span class="two"></span> <span class="three"></span> <span class="four"></span> </div> The tools I have available are JS and YUI2.(我可用的工具是JS和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'); These do not work in IE.(这些在IE中不起作用。) I get an error that the object (doc) doesn't support this method or property (getElementsByClassName).(我得到一个错误,对象(doc)不支持此方法或属性(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的跨浏览器实现的例子,但是我无法使它们工作并且仍然有错误。) 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.(我认为我需要的是一个跨浏览器getElementsByClassName或者我需要使用doc.getElementsByTagName('span')并循环直到我找到第4类。我不知道如何做到这一点。)   ask by spyderman4g63 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use querySelector and querySelectorAll(使用querySelector和querySelectorAll)

var testContainer = document.querySelector('#test'); var fourChildNode = testContainer.querySelector('.four'); IE9 and upper(IE9和上层) ;)(;))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...