Categories
JavaScript Answers

How to Select a Span Containing a Specific Text Value Using jQuery?

Spread the love

To select a span containing a specific text value using jQuery, we can select all the spans and then use the filter method to find the one with the given text value.

For instance, if we have the following HTML:

<div>
  <span>FIND ME</span>
  <span>dont find me</span>
</div>

and we want to find the span with the text FIND ME , then we can write:

const findMe = [...$("span")].filter((el) => {
  return $(el).text().includes('FIND ME')
})
console.log(findMe)

We call $(“span”) to get all the spans.

Then we spread the spans into an array with the spread operator.

Next, we call filter with a callback that takes the el element and calls text on the element once it’s put into the $ function to get the text.

Then we call includes with 'FIND ME' to check for the text.

This will find the span that has FIND ME anywhere in the element.

If we want to find an exact match, we write:

const findMe = [...$("span")].filter((el) => {
  return $(el).text() === 'FIND ME'
})

In either case, it’ll return an array with the span with the text FIND ME .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.