下面是我想从中获取元素的代码,我使用了代码
var elements = document.getElementsByClassName('highlight');
我得到了“highlight”类的所有元素,但我想选择所有在span标签中包含“Green Leafy veggies”的元素,并且类只作为highlight。
<html>
<body>
<style>
.highlight {
color: blue;
font-weight: bold;
}
.highlight2 {
color: green;
font-weight: bold;
}
</style>
<p>This is the health benefits of <span class='highlight'>Green leafy veggies</span> hope you kids eat them.</p>
<p>This is the health benefits of <span class='highlight2'>Green leafy veggies</span> hope you kids eat them.</p>
<p>This is the health benefits of <span class='highlight'>Green leafy veggies</span> hope you kids eat them.</p>
<p>This is another <span class='highlight'>Green leafy veggies</span>tag</p>
</body>
</html>
预先感谢您的回答
您需要从元素的集合中创建一个数组(Array.from
用于它),并用于filter
获取所需的元素:
var elements =
Array.from(document.getElementsByClassName('highlight'))
.filter(element => element.innerText === 'Green leafy veggies');
console.log(elements.length);
.highlight {
color: blue;
font-weight: bold;
}
.highlight2 {
color: green;
font-weight: bold;
}
<p>This is the health benefits of <span class='highlight'>Red leafy veggies</span> hope you kids eat them.</p>
<p>This is the health benefits of <span class='highlight2'>Green leafy veggies</span> hope you kids eat them.</p>
<p>This is the health benefits of <span class='highlight'>Green leafy veggies</span> hope you kids eat them.</p>
<p>This is another <span class='highlight'>Green leafy veggies</span>tag</p>
编辑 1
要查找包含文本Leafy 的所有元素,您只需将其替换element.innerText === 'Green leafy veggies'
为/leafy/.test(element.innerText)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句