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:
JavaScript
x
3
1
var spanExist = $('#activityDiv :span[text="hello"]').length;
2
alert("span exists : " + spanExist);
3
but it gives the following error in console:
Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: span
Advertisement
Answer
Use :contains()
pseudo-class selector.
JavaScript
1
3
1
var spanExist = $('#activityDiv span:contains("hello")').length;
2
alert("span exists : " + spanExist);
3
If you want to get only elements with the exact match of text then use filter()
method.
JavaScript
1
6
1
var spanExist = $('#activityDiv span:contains("hello")').filter(function(){
2
return $(this.text().trim() == "hello";
3
}).length;
4
5
alert("span exists : " + spanExist);
6