0

How can I get DIV id or DIV class using Jquery if the HTML is similar to:

<div class="first" id="first_id">
<div class="second">text sample</div>
<div class="third"><button type="submit" class="some_class" id="some_id" >send</button></div>
</div>

Is it possible to get the class or ID of the div "first", with the click of the button?

I know that using this Jquery code I'll get the button ID, but can I get, with some changes in this code, alert message with the class (or id) od "first" DIV?

$("#some_id").click(function() {
var test=$(this).attr('id');
alert(test);
return false;
});

1 Answer 1

6

Use .closest(selector) to crawl up to that parent, like this:

$("#some_id").click(function() {
  var test = $(this).closest('.first').attr('id');
  alert(test);
  return false;
});

You can give it a try here. This crawls up the parents until one matches the .first selector, then just grab that element's ID.

Sign up to request clarification or add additional context in comments.

1 Comment

When I last crawled up to my parents I was two years old!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.