Search code examples
javascripthtmljqueryarraysshow-hide

Hide parent element not containing specific text


I am trying to hide parent elements using ID of child as selector; if they do not contain specific text. In this case *. Must be this way and have to use jQuery.

So far I have this:

HTML

<div>
    <label>
        First name <font color="red">*</font>
        <input type="text" id="guest_first_name">
    </label>
</div>

</br>

<div>
    <label>
        Last name 
        <input type="text" id="guest_last_name">
    </label>
</div>

jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>

<script>
 $(document).ready(function() {

    let checkthis = $("#guest_first_name, #guest_last_name").parent();  
    var removewithout = "*";
    checkthis.not(removewithout).hide();

 })

</script>

Struggling to check elements that do not contain text and then hide. Trying to hide <label> with text Last name as it does not contain *. Hope this is clear. Any help is appreciated.

Thanks


Solution

  • The .not() method accepts selectors, jQuery objects, and functions.

    $(document).ready(function() {
    
      let checkthis = $("#guest_first_name, #guest_last_name").parent();
      var removewithout = /\*/;
      checkthis.not((i, e) => removewithout.test(e.innerHTML)).hide();
    
    })

    Reference: