firasKoubaa firasKoubaa - 3 months ago 8
jQuery Question

jQuery : How to return an element by the value of a class of its child

i have a block of buttons , and i wanna return the name of the parent "li" which is containing the button (a) with the class "is active"

<li class="page" name="1"><a href="#" class="is-active">1</a></li>
<li class="page" name="2"><a href="#">2</a></li>
<li class="page" name="3"><a href="#">3</a></li>
<li class="page" name="4"><a href="#">4</a></li>
<li class="page" name="5"><a href="#">5</a></li>


i want to return in this case the first element with name "1".

i have tried
attr("class", "is-active")
and
the method find().class("is-active")

but that didn't work

any suggestions ??

Answer

:has() filter will do it

console.log(

 $('.page:has(.is-active)').attr('name')

)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<li class="page" name="1"><a href="#" class="is-active">1</a></li> 
<li class="page" name="2"><a href="#">2</a></li>
<li class="page" name="3"><a href="#">3</a></li>
<li class="page" name="4"><a href="#">4</a></li>
<li class="page" name="5"><a href="#">5</a></li>