如何在jquery中通过span文本获取div的跨度

时间:2021-12-02 08:44:58

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

我有一个div,我有一些跨度。现在我需要根据它的文本找到特定的跨度。但不能这样做。有人可以帮我这个吗?以下是我在以下的尝试>>>

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

未捕获错误:语法错误,无法识别的表达式:unsupported pseudo:span

2 个解决方案

#1


4  

Use :contains() pseudo-class selector.

使用:contains()伪类选择器。

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.

如果您只想获得具有完全匹配文本的元素,请使用filter()方法。

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

alert("span exists   : " + spanExist);

#2


0  

This might help

这可能有所帮助

$(document).ready(function(){

var spanExist = $('#activityDiv span').text().trim();
if(spanExist == 'Hello'){
    alert("span exists   : " + spanExist);
}


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='activityDiv'> 
  <span>Hello</span> <br/>
  
  
  
  </div>

#1


4  

Use :contains() pseudo-class selector.

使用:contains()伪类选择器。

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.

如果您只想获得具有完全匹配文本的元素,请使用filter()方法。

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

alert("span exists   : " + spanExist);

#2


0  

This might help

这可能有所帮助

$(document).ready(function(){

var spanExist = $('#activityDiv span').text().trim();
if(spanExist == 'Hello'){
    alert("span exists   : " + spanExist);
}


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='activityDiv'> 
  <span>Hello</span> <br/>
  
  
  
  </div>