我试图得到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。但我不知道该怎么做。


当前回答

从这里使用YAHOO.util.Dom.getElementsByClassName()。

其他回答

另一种方式

const result = [...(parentElement.children)].find(child => {
  return child.classList.contains('some-class-name');
});

首先,我们展开NodeList的元素,将其转换为Array,以便使用find()方法。最后,find()将返回classList属性包含给定类名的第一个元素。

在我看来,只要可以,就应该使用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
})

使用文档。childNodes遍历每个span,然后筛选className = 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;
    }        
}

2018年6月更新至ES6

    const doc = document.getElementById('test');
    let notes = null;
    for (const value of doc) {
        if (value.className === '4') {
            notes = value;
            break;
        }    
    }

在我看来,你想要的是第四张成的空间。如果是这样,你可以这样做:

document.getElementById("test").childNodes[3]

or

document.getElementById("test").getElementsByTagName("span")[3]

最后一个方法确保没有任何隐藏的节点会把它搞砸。