Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get id of element by searching for it by class

This is my html :

<div id="my_box_one" class="head-div">
   <div>
       <div class="some_box">a</div>
       <div class="some_box">b</div>
    </div>
</div>

I want to get the ID of the parent div("#my_box_one") using the class of that div(".head-div")

$(document).ready(function(){

$(".some_box").click(function(){
   var abc = $(this).parentsUntil(".head-div").attr("id");
   // also tried $(this).parent(".head-div") -- same effect
   alert(abc); // Shows as Undefined
});   

});

I can do the following and it will work okay, but it doesn't seem right.

var abc = $(this).parent("div").parent("div").attr("id");
like image 486
DMin Avatar asked Apr 30 '11 12:04

DMin


People also ask

How can I get the ID of an element using jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do I find the ID of a selected element?

getElementById() The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

How do I know which ID is clicked in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to get or set the ID attribute value of an element. The following example will display the ID of the DIV element in an alert box on button click.

How can get li id value in jQuery?

Show activity on this post. $('#loadMore'). on('click', function () { var page = $('#page'); var msg = $('#loadMoreMsg'); alert($(this). attr('id')); return false; });


1 Answers

You can use .closest( selector ), for example:

var abc = $(this).closest(".head-div").attr("id");

http://api.jquery.com/closest/

.parent( selector ) selects only immediate parent of the element.

like image 200
Lapple Avatar answered Oct 21 '22 01:10

Lapple