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


当前回答

另一种方式

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

现代的解决方案

const context = document.getElementById('context');
const selected = context.querySelectorAll(':scope > div');

文档

使用querySelector

var doc=document.getElementById(“test”); console.log(doc.querySelector('.two').innerHTML) <div id=“test”> <span class=“one”></span> <span class=“two”>two</span> <span class=“three”></span> <span class=“four”></span> </div> 使用 querySelectorAll

var doc=document.getElementById(“test”); console.log(doc.querySelectorAll('*')[1].innerHTML) <div id=“test”> <span class=“one”></span> <span class=“two”>two</span> <span class=“three”></span> <span class=“four”></span> </div>

使用getelementsbytagname

var doc=document.getElementById(“test”); console.log(doc.getElementsByTagName(“SPAN”)[1].innerHTML); <div id=“test”> <span class=“one”></span> <span class=“two”>two</span> <span class=“three”></span> <span class=“four”></span> </div> <span>党卫军</span>

使用getElementsByClassName

var doc=document.getElementById(“test”); console.log(doc.getElementsByClassName('two')[0].innerHTML) <div id=“test”> <span class=“one”></span> <span class=“two”>two</span> <span class=“three”></span> <span class=“four”></span> </div>

Let notes = document。querySelector(“#测试.four”)

您可以通过添加下面的行来获取父类。如果您有一个id,那么使用getElementById会更容易。尽管如此,

var parentNode = document.getElementsByClassName("progress__container")[0];

然后你可以在父类<div>上使用querySelectorAll来获取所有匹配的div类。progress__marker

var progressNodes = progressContainer.querySelectorAll('.progress__marker');

querySelectorAll将获取progress__marker类的每个div