TruthOf42
TruthOf42

Reputation: 2107

Determine what class is a closer ancestor of an element

How can I determine what class is a closer ancestor of an element in jquery?

I can easily do

$("#elementID").closest(".class1")

and

$("#elementID").closest(".class2")

but this doesn't tell me which one was found first

Upvotes: 0

Views: 29

Answers (2)

Spera
Spera

Reputation: 91

Multiple selectors are supported by JQ. Just separate the selectors by a comma.

https://api.jquery.com/multiple-selector/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="class1">
  <div class="class2">
    <div id="elementID">
    </div>
  </div>
</div>

<script>
  alert($("#elementID").closest(".class1, .class2")[0].className)
</script>

Upvotes: 1

fstanis
fstanis

Reputation: 5554

Remember, you can use any selector in .closest(...) and jQuery will stop as soon as it matches that selector, so...

$("#elementID").closest(".class1, .class2")

...is what you want.

Upvotes: 3

Related Questions