Filippo oretti
Filippo oretti

Reputation: 49883

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>
    <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

Answers (5)

Daniel Brockman
Daniel Brockman

Reputation: 19290

$(".second").has(".tg-hey").length > 0

Upvotes: 2

karim79
karim79

Reputation: 342795

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.

Upvotes: 5

josh.trow
josh.trow

Reputation: 4901

Like this?

if ($('ul.second div.tg-hey').length > 0)
  // exists
else
  // doesn't

Upvotes: 1

Richard Dalton
Richard Dalton

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");
}

http://jsfiddle.net/SgnvH/

Upvotes: 4

MattW
MattW

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

Related Questions