Reputation: 7490
HTML:
<div id="aaa" class="p">
<div id = "bbb">
<div id="actor" onclick = "testParent(this)">
test parent
</div>
</div>
</div>
JS:
testParent = function(obj){
alert($(obj).parent(".p").id);
}
I think this should be alerting aaa
but it doesn't.
Isn't this a way to find parent by class?
Edit I know closest can do this but more specifically it is parent, isn't it? So there is no specific implementation from jquery for this?
Upvotes: 1
Views: 2483
Reputation: 597
Try:
testParent = function(obj){
alert($(obj).parents('.p').attr('id'));
}
It's pretty simple and short code.
Upvotes: 3
Reputation: 2462
Use need to use parents()
it will find matching parent with class
.p
and attr()
will get you id of matched parent. See below code.
testParent = function(obj){
alert($(obj).parents(".p").attr("id"));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="aaa" class="p">
<div id = "bbb">
<div id="actor" onclick = "testParent(this)">
test parent
</div>
</div>
</div>
Upvotes: 2
Reputation: 2498
try this code
JAVASCRIPT-
testParent = function(obj){
alert($(obj).closest(".p").attr('id'));
}
Upvotes: 1
Reputation: 4938
You have to use .closest()
and use the obj
without the $()
It should be like this:
alert(obj.closest(".p").id);
testParent = function(obj) {
alert(obj.closest(".p").id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="aaa" class="p">
<div id="bbb">
<div id="actor" onclick="testParent(this)">
test parent
</div>
</div>
</div>
Upvotes: 1