Search code examples
jqueryelementselectorhidden

How to use selector to check all elements start with similar id is hidden in Jquery?


<div id="reply_div1"> </div>
<div id="reply_div2"> </div>
<div id="reply_div3"> </div>
<div id="reply_div4"> </div>

This one works:

if ($('#reply_div1').is(":hidden") 
    && $('#reply_div2').is(":hidden") 
    && $('#reply_div3').is(":hidden") 
    && $('#reply_div4').is(":hidden"))
{
      #do something
}

But this one does not work:

if ($("div[id^='reply_div']").is(":hidden"))
{
      #do something
}

How to use selector to check all elements start with reply_div are hidden?


Solution

  • To determine if all elements of a specific set are hidden you can use the :visible selector, then test if the length of found elements is 0.

    if ($('div[id^="reply_div"]:visible').length === 0) {
      console.log('all hidden');
    } else {
      console.log('not all hidden');
    }
    #reply_div1, 
    #reply_div2, 
    #reply_div3, 
    #reply_div4 {
      display: none;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="reply_div1">1</div>
    <div id="reply_div2">2</div>
    <div id="reply_div3">3</div>
    <div id="reply_div4">4</div>