下面是我要从中获取元素的代码,我使用了代码

var elements = document.getElementsByClassName('highlight');


我得到了“亮点”类的所有元素,但我想选择所有在span标签中具有“绿叶蔬菜”的元素,而类仅作为突出显示。

<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

要查找包含多叶文本的所有元素,只需将element.innerText === 'Green leafy veggies'替换为/leafy/.test(element.innerText)

07-22 01:50