Skip to content
Advertisement

How to get a span from a div by span text in jQuery

I have a div where I have some span. Now I need to find a specific span based on its text. What can I try next? Here are my attempts below:

var spanExist = $('#activityDiv :span[text="hello"]').length;
alert("span exists   : " + spanExist);

but it gives the following error in console:

Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: span

Advertisement

Answer

Use :contains() pseudo-class selector.

var spanExist = $('#activityDiv span:contains("hello")').length;
alert("span exists   : " + spanExist);

If you want to get only elements with the exact match of text then use filter() method.

var spanExist = $('#activityDiv span:contains("hello")').filter(function(){
   return $(this.text().trim() == "hello";
}).length;

alert("span exists   : " + spanExist);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement