简体   繁体   English

如何使用 text() 查找元素

[英]How to find element using text()

I'm wondering if it's possible to hide the parent div based on child text content?我想知道是否可以根据子文本内容隐藏父 div?

 //$('div >.tree-title').hide();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <span>1</span> <span></span> <span class="tree-title">Hello</span> </div> <div class="container"> <span>2</span> <span></span> <span class="tree-title">World</span> </div>

In this case I would like to hide the second div because the class .tree-title contain World text.在这种情况下,我想隐藏第二个 div,因为 class .tree-title包含World文本。

You can use jQuery's :contains() and .parent()您可以使用 jQuery 的:contains().parent()

 $('div >.tree-title:contains(World)').parent().hide();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <span>1</span> <span></span> <span class="tree-title">Hello</span> </div> <div class="container"> <span>2</span> <span></span> <span class="tree-title">World</span> </div>

Using contains :使用包含

$('div > .tree-title:contains("World")').parent().hide();

Using filter :使用过滤器

$('.tree-title').contents().filter(function(){
  return $(this).text().trim() == 'World';
}).parents('container').hide();

Using :has and :contains Selector使用:has:contains选择器

 $('div:has(.tree-title:contains(World))').hide();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="container"> <span>1</span> <span></span> <span class="tree-title">Hello</span> </div> <div class="container"> <span>2</span> <span></span> <span class="tree-title">World</span> </div>

You can also:你也可以:

$('.tree-title').each(function() {
  if($(this).text() === 'World') {
    $(this).parent().hide();
  }
});

Hope it helps:)希望能帮助到你:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM