Sumon Bappi Sumon Bappi - 10 months ago 44
Javascript Question

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 it's text. But can't do it. Can anyone please help me on this please? 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

Answer Source

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";

alert("span exists   : " + spanExist);