Reputation: 49883
Hi my html looks like this:
<ul class="first">
<li>
<div class="tg-hey">hey</div>
<div class="tg-hi">hi</div>
<div class="tg-hoi">hoi</div>
</li>
</ul>
<ul class="second">
<li>
<div class="tg-hey">hey</div>
<div class="tg-hi">hi</div>
<div class="tg-hoi">hoi</div>
</li>
</ul>
<ul class="third">
<li>
<div class="tg-hey">hey</div>
<div class="tg-hi">hi</div>
<div class="tg-hoi">hoi</div>
</li>
</ul>
what i need is to find if (for example in <ul class="second">
) the <div class="tg-hey">
exist or not.
how can i check it?
Upvotes: 2
Views: 900
Reputation: 342795
if($(".second:has(.tg-hey)").length) {
// do something
}
If you need to do something to the matching element(s), you don't really need to test first, since nothing will happen if there are no matches, so:
$(".second:has(.tg-hey)").hide();
is perfectly safe.
Another way is to use .is
and :has
:
if($(".second").is(":has(.tg-hey)")) {
// do something
}
but I wouldn't do that since it just seems like too much jQuery for a fairly simple task.
Upvotes: 5
Reputation: 4901
Like this?
if ($('ul.second div.tg-hey').length > 0)
// exists
else
// doesn't
Upvotes: 1
Reputation: 35803
Just create the selector and check the length of the result (if it is 0 it will be false, otherwise it is true):
if ($('ul.second div.tg-hey').length) {
alert("It exists");
}
Upvotes: 4
Reputation: 13212
$('.className').length
if $('.className').length == 0
, then the element does not exist.
Edit:
$('.second').length
will tell you how many elements have the class "second".
$('.second .tg-hey').length
will tell you how many elements have the class "tg-hey" inside the class "second".
This assumes that you are using jQuery!
Upvotes: 0