jQuery get id of element by searching for it by class

℡╲_俬逩灬. 提交于 2019-11-30 03:35:48

问题


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");

回答1:


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.




回答2:


parentsUntil gets all the parent elements until the one matched by the selector. It does not include the element matched. You're trying to get the id of the intervening div, which is obviously undefined.

You need to use closest, which goes up the DOM tree until it finds an element matching the selector, then returns only that element:

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

Edit: for extra speed, but less flexibility in the event that you change your markup, you could use the parentNode property:

var abc = this.parentNode.parentNode.id;


来源:https://stackoverflow.com/questions/5841650/jquery-get-id-of-element-by-searching-for-it-by-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!