我试图得到class = 4的子span。下面是一个示例元素:
<div id="test">
<span class="one"></span>
<span class="two"></span>
<span class="three"></span>
<span class="four"></span>
</div>
我可用的工具是JS和YUI2。我可以这样做:
doc = document.getElementById('test');
notes = doc.getElementsByClassName('four');
//or
doc = YAHOO.util.Dom.get('#test');
notes = doc.getElementsByClassName('four');
这些在IE中不起作用。我得到一个错误,对象(doc)不支持此方法或属性(getElementsByClassName)。我已经尝试了几个跨浏览器实现getElementsByClassName的例子,但我不能让他们工作,仍然得到了这个错误。
我认为我需要的是一个跨浏览器getElementsByClassName或我需要使用doc.getElementsByTagName('span')和循环,直到我找到类4。但我不知道该怎么做。
在我看来,只要可以,就应该使用Array及其方法。它们比遍历整个DOM /包装器或将东西推入空数组快得多。这里提出的大多数解决方案都可以调用Naive(顺便说一句,这是一篇很棒的文章):
https://medium.com/@chuckdries/traversing-the-dom-with-filter-map-and-arrow-functions-1417d326d2bc
我的解决方案:(在Codepen上的实时预览:https://codepen.io/Nikolaus91/pen/wEGEYe)
const wrapper = document.getElementById('test') // take a wrapper by ID -> fastest
const itemsArray = Array.from(wrapper.children) // make Array from his children
const pickOne = itemsArray.map(item => { // loop over his children using .map() --> see MDN for more
if(item.classList.contains('four')) // we place a test where we determine our choice
item.classList.add('the-chosen-one') // your code here
})
在我看来,只要可以,就应该使用Array及其方法。它们比遍历整个DOM /包装器或将东西推入空数组快得多。这里提出的大多数解决方案都可以调用Naive(顺便说一句,这是一篇很棒的文章):
https://medium.com/@chuckdries/traversing-the-dom-with-filter-map-and-arrow-functions-1417d326d2bc
我的解决方案:(在Codepen上的实时预览:https://codepen.io/Nikolaus91/pen/wEGEYe)
const wrapper = document.getElementById('test') // take a wrapper by ID -> fastest
const itemsArray = Array.from(wrapper.children) // make Array from his children
const pickOne = itemsArray.map(item => { // loop over his children using .map() --> see MDN for more
if(item.classList.contains('four')) // we place a test where we determine our choice
item.classList.add('the-chosen-one') // your code here
})