如何在课程的span标签中选择内容

时间:2018-08-24 12:57:34

标签: javascript jquery html css

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

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>

预先感谢您的回答

2 个答案:

答案 0 :(得分:2)

您将需要从元素集合中创建一个数组(使用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)

答案 1 :(得分:1)

因为您提到了jQuery标签

您可以选择contains

var elements = $('.highlight:contains("Green leafy veggies")');