I try get id parent p div (class mainRow), but my code in console return undefinied:
<div class="row mainRow" id="someId">
<div class="selected">
<p onclick="checkParentId(this)">Hello</p>
</div>
</div>
<script>
function checkParentId(element){
var a = $(element).parent( ".mainRow");
var b = $(a).attr("id");
console.log(b);
}
</script>
Link to jsfiddle: https://jsfiddle.net/50ev1jzq/
3
Answers
I find sollution, i change .parent to .closest and code work
Since the
.mainRow
is not a parent of the paragraph, use.closest
:You could use
parents()
, because according to the docs:As others have pointed out,
closest()
could also work. There are some differences tough: