如何选择类的span标签中的内容

瓦姆西香卡

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

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>

预先感谢您的回答

31piy

您需要从元素的集合中创建一个数组(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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Selenium XPath:如何在 span 类标签中查找文本?

如何在span标签中返回添加CSS类

如何通过之前的标签内容选择标签?

如何将span标签和类保留在TinyMce中的预代码块中

选择重复的'span'标签

如何从与其他类同名的span类中按标签获取元素?

在BeautifulSoup中提取多个Span标签中的内容

如何在span标签中写入值?

如何从span标签中抓取字典?

如何使用BeautifulSoup选择href类标签?

为什么相同的文本内容在<input>中显示的内容与在<div>或<span>标签中显示的内容不同?

如何更改div中的span内容

如何在JavaScript中使用Selenium中的certian类从标签中获取内容

选择嵌套在多个div块中的span标签

span类中输入标签(单选按钮)的Xpath

如何通过更改“选择”标签中的某些内容来更新字段?

如何在HTML中添加没有输入标签的选择字段所需的内容

如何获取具有特定类后缀的 span 元素的内容?

选择后如何将提及内容包装在特殊的跨度标签中?像Facebook或Stackoverflow标签

如何从每个选择元素选项中检索文本内容并动态分配给div> span元素

如何调整在类路径资源中选择的标签中的图像大小?

如何通过使用python硒获取span标签(如<span> Test </ span>)中的文本?

如何从标签中获取for属性的内容?

如何将标签中的内容居中

如何根据标签在UItableView中的内容

如何操作Dom只选择标签内的文本内容?

如何从 r 中的 span & p 标签中检索文本

RVest:从超市网页中提取类中的标签内容

如何根据从下拉列表中选择的内容(ASP.NET中的C#)更改标签的输出