如何根据内容选择HTML元素中的文本

How to select text inside an HTML element, based on content?

本文关键字:元素 文本 HTML 选择 何根      更新时间:2023-09-26

我想找到有多少产品在一个网站内的列表或数组。我想要的是Course它是<strong >元素中的文本

我可以选择他们,但我怎么能过滤只有单词COURSE我使用开发工具在我的浏览器。

代码如下:

我使用var e = document.querySelectorAll('.card-type');类的选择器

`[<strong class=​"card-type">​Workshop​</strong>​, 
 <strong class=​"card-type">​Course​</strong>​, 
 <strong class=​"card-type">​Workshop​</strong>​,
 <strong class=​"card-type">​Course​</strong>​,
 <strong class=​"card-type">​Workshop​</strong>​, 
 <strong class=​"card-type">​Workshop​</strong>​,
 <strong class=​"card-type">​Workshop​</strong>​,
 <strong class=​"card-type">​Workshop​</strong>​,
 <strong class=​"card-type">​Course​</strong>​, 
 <strong class=​"card-type">​Workshop​</strong>​,
 <strong class=​"card-type">​Course​</strong>​,
 <strong class=​"card-type">​Course​</strong>​, 
 <strong class=​"card-type">​Course​</strong>​,
 <strong class=​"card-type">​Course​</strong>​,
 <strong class=​"card-type">​Course​</strong>​,
 <strong class=​"card-type">​Course​</strong>​ ​]` 

filter过滤列表

let courses = e.filter(item => item.textContent === "Course");

这是使用letfat arrow syntax又名lambda,这是ES6语法。如果你想要ES5 JavaScript,只需使用var和一个普通的匿名函数。

var courses = e.filter(function(item) {
    return item.textContent === "Course";
});
编辑:Kevin B发现我的功能将是未定义的,他是正确的。这是因为eNodeList而不是数组。我们必须转换它!有多种方法可以将NodeList转换为数组。最简单的是splice。或者您也可以使用spread语法[...e].filterArray.from(),它们都是ES6的功能。

我是这样一步步回答的:

  1. 选择我想要的元素:
    var e = document.querySelectorAll('.card-type');
  2. 将变量放入数组中:
    const f = Array.apply(null, e);
  3. 现在过滤器与新数组:
    let courses = f.filter(item => item.textContent === 'Courses');

2选项如果你不想转换为ARRAY,只需循环NodeList。

let course = document.querySelectorAll('.card-type');  
 

使用旧的For循环

for(let i = 0; i < course.length; i++) {
   console.log(course.item(i).innerText)
}

And IF语句获取COURSE word ONLY

for (let i =0; i < course.length; i++) {
     if(course.item(i).innerHTML == "Course") 
     {
        console.log(course.item(i));
     }
}

使用jquery,你可以只用几行,使用.text().each()

$('.card-type').each(function(el, i) {
  var text = $(el).text();
    if (text == "Course") {
       console.log("found it");
    }
});

基本上,您遍历列表中的所有元素,然后检查每个元素的内容是否正确,并对其进行其他操作。

您可以使用其他功能,如向下过滤,但这完全取决于您希望对元素做什么。