简体   繁体   中英

Hiding a div if another contains a specific string in jQuery

I want to check if an element on page contains a text phrase, it shows a second hidden container? For example, '#product-description' contains 'best gift' then a hidden container '#best-gift-graphic' over the product image is shown. I've found answers that skirt around this, and tackle parts, but I can't seem to put it all together.

I've found solutions that hide the element that contains the text:

<script type="text/javascript">
 $(document).ready(function () {
  $("div p:contains('text')").parent('div').hide();
 });
</script>

I need to apply the show/hide to a second container, not the container with the target phrase in. Really new to jquery and just want to understand the syntax. Thanks in anticipation.

You need to check the length to see if any items exist, you can then use .hide() to hide your corresponding element if there is any:

 if ($('#product-description:contains("best gift")').length) { // check if this exists $('#best-gift-graphic').hide(); // hide this } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="product-description">best gift</div> <div id="best-gift-graphic">this is hidden</div> 

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