How to get the name of the last father div with parents?

Asked

Viewed 1,929 times

2

I have a sequence of Ivs like the ones below.

<div class="upage" id="id01">
 <div class="main" id="id02">
   <div class="main2" id="id03">
   </div>   
 </div>
</div>

I need to get the id of the class that is above in this case should returns id01. I use the parents(".upage"); but he comes to me a pointer with the whole div. I need to get only the ID.

How to do ?

  • What is the starting point element? Perhaps the closest() be the best? .closest('.upage').attr('id');

  • The starting point is an input with Focus.

1 answer

3


I suggest you use the .closest() which takes an argument that can be a class. Then the attr('id') that retrieves the ID of the element that .closest() returned.

$('input').on('focus', function(){
    var id = $(this).closest('.upage').attr('id');
    // fazer algo com o id
});

Example: https://jsfiddle.net/gby3944g/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.