Alejandro Ruiz Aviña Alejandro Ruiz Aviña - 3 months ago 6
jQuery Question

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

I want to find how many products are in a list or array inside a website. The one I want to it's called

Course
which is text inside the
<strong >
element.

I can select them all but how can I filter just the ones with the word COURSE I'm using development tools inside my browser.

Here is the code:

I use a selector for the class
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>​ ​]`

Answer

Filter your list with filter.

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

This is using let and fat arrow syntax aka a lambda which are ES6 syntax. If you want ES5 JavaScript, simply use var and a normal anonymous function.

var courses = e.filter(function(item) {
    return item.textContent === "Course";
});

Edit: Kevin B spotted that my function will be undefined and he his right. That is because e is a NodeList and not an array. We have to convert it! There are multiple ways to convert a NodeList to an array. The easiest being splice. Or you can get fancy and use spread syntax [...e].filter or Array.from() as well, which are both also ES6 features.

Comments