Musa Muaz
Musa Muaz

Reputation: 714

Checking if a div has child element - Jquery

I need to check if a div has a child element and then add CSS (display: none).

But my code is working neither with single or double equal character.

<div class="flex-video mb-30 "> 

</div>

And my codes are :

if ($(".flex-video").children().length == 0) {
    $(this).css('display', 'none');
}

Upvotes: 1

Views: 1563

Answers (4)

Josh Crozier
Josh Crozier

Reputation: 240878

It's not working as expected because this doesn't refer to the element that you are trying to target. By default, this refers to the window object, and without seeing your full code, that is probably what is happening.

You could either re-specify the jQuery selector:

if ($(".flex-video").children().length === 0) {
    $(".flex-video").css('display', 'none');
}

...or store the jQuery selector in a variable:

var $flexVideo = $(".flex-video")
if ($flexVideo.children().length === 0) {
    $flexVideo.css('display', 'none');
}

However, it's worth pointing out that the two snippets above wouldn't work if there are multiple .flex-video elements because you are only checking the first one. It would be better to iterate over all of the .flex-video elements in case there is more than one.

In the snippet below, this is bound to the current .flex-video element that is being iterated over because the .each() method provides context for the this value:

$(".flex-video").each(function () {
  if ($(this).children().length === 0) {
    $(this).css('display', 'none');
  }
});

Alternatively, you could also make the conditional check within the context of the .css() method because this will be bound to the .flex-video element. Internally, jQuery will iterate over all of the elements similar to the .each() method example above.

$(".flex-video").css('display', function() {
  return $(this).children().length === 0 ? 'none': '';
});

Upvotes: 0

Snowmonkey
Snowmonkey

Reputation: 3761

Couldn't you simply do:

$(".flex-video :not(:has(*) )").hide();

or:

$(".flex-video :empty").hide();

Upvotes: 1

Loveen Dyall
Loveen Dyall

Reputation: 834

try

$.each($('.flex-video'), function(idx, ele) {
    if ($(ele).children().length == 0) {
        $(ele).css({"display": "none"});
    }
});

This iterates through each element with class .flex-video and assigns to ele, if ele doesn't have children, it sets display property to none.

Upvotes: 0

Michael Coker
Michael Coker

Reputation: 53674

$(this) doesn't refer to .flex-video in your code. I would assign that element to a variable, then just reference the variable in the rest of your code.

var $flexVideo = $(".flex-video");
if ($flexVideo.children().length == 0){
    $flexVideo.css('display', 'none');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex-video mb-30 "> 
</div>

Upvotes: 0

Related Questions