Sumon Bappi Sumon Bappi - 1 year ago 98
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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download