简体   繁体   中英

How to find element using text()

I'm wondering if it's possible to hide the parent div based on child text content?

 //$('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.

You can use jQuery's :contains() and .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

 $('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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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