Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if element has no children with jquery

I want to check if element has no children set parents element display:none property.

But my js is not working as expect where is my mistake ?

$(document).ready(function(){
  if (!$('#detay-main-carousel').children('.carousel-inner').length>1) {
     $('#detay-main-carousel').hide();
  }
});
<div id="detay-main-carousel" style="background:turquoise;">
  <div class="carousel-inner">
    This is the slider.....
  </div>
</div>

<div id="detay-main-carousel" style="background:yellow;">
    This is the slider.....
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 984
ani_css Avatar asked Oct 27 '25 10:10

ani_css


2 Answers

The id detay-main-carousel is duplicate.

Also ! ..children('.carousel-inner').length > 1 should be:

! ..children('.carousel-inner').length OR children('.carousel-inner').length < 1 OR children('.carousel-inner').length === 0

$(document).ready(function(){
  $('.detay-main-carousel').each(function () {
    if (!$(this).children('.carousel-inner').length) {
        $(this).hide();
    }
  })
});
<div class="detay-main-carousel" style="background:turquoise;">
  <div class="carousel-inner">
    This is the slider.....
  </div>
</div>

<div class="detay-main-carousel" style="background:yellow;">
    This is the slider.....
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
like image 131
Mohamed Abbas Avatar answered Oct 30 '25 00:10

Mohamed Abbas


The ! operator has a higer precedence than >, so you should write it differently:

if ($('#detay-main-carousel').children('.carousel-inner').length<=1) {

which would be the exact opposite of the >1 check. But reading your question, you would want to test for no such children at all (excluding 1):

if ($('#detay-main-carousel').children('.carousel-inner').length == 0) {

Note that $('#detay-main-carousel') will only match the first occurrence since id values are supposed to be unique. Better replace your id values with classes, so they don't have to be unique.

like image 33
trincot Avatar answered Oct 29 '25 23:10

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!