jQuery search if found element child
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>
<开发者_JAVA百科;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?
if($(".second:has(.tg-hey)").length) {
// do something
}
Demo.
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
}
Demo.
but I wouldn't do that since it just seems like too much jQuery for a fairly simple task.
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");
}
http://jsfiddle.net/SgnvH/
$(".second").has(".tg-hey").length > 0
Like this?
if ($('ul.second div.tg-hey').length > 0)
// exists
else
// doesn't
$('.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!
精彩评论