tags:

views:

51

answers:

1

Hi,

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;
});
+5  A: 

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.

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