I am trying to access the nearest div from the anchor tag that has a data-id attribute.
.parent().parent().parent()
works but I am really trying to avoid doing that.
<div class="panel panel-default" data-id="@customer.Id">
<div class="panel-heading clearfix">
@customer.Name
<div class="pull-right">
<a class="btn btn-sm btn-default js-deleteCustomer" href="#" title="Delete">
<i class="fa fa-trash" aria-hidden="true"></i>
</a>
</div>
</div>
I tried the following:
var customerId = $(this).closest("div:has(*[data-id])").attr('data-id');
I am trying to access the nearest div from the anchor tag that has a data-id attribute.
.parent().parent().parent()
works but I am really trying to avoid doing that.
<div class="panel panel-default" data-id="@customer.Id">
<div class="panel-heading clearfix">
@customer.Name
<div class="pull-right">
<a class="btn btn-sm btn-default js-deleteCustomer" href="#" title="Delete">
<i class="fa fa-trash" aria-hidden="true"></i>
</a>
</div>
</div>
I tried the following:
var customerId = $(this).closest("div:has(*[data-id])").attr('data-id');
Share
Improve this question
edited Jul 9, 2017 at 16:55
BoltClock
725k165 gold badges1.4k silver badges1.4k bronze badges
asked Jul 9, 2017 at 16:50
Blake RivellBlake Rivell
13.9k33 gold badges130 silver badges261 bronze badges
1 Answer
Reset to default 7You want
var customerId = $(this).closest("div[data-id]").attr('data-id');
:has(*[data-id])
doesn't match an element with that attribute. It matches an element that contains another element with that attribute. The element that's matched probably doesn't have this same attribute, which would explain why :has(*[data-id])
doesn't work. For instance, it would match the outer div, not the inner div, in the following:
<div>
<div data-id="@customer.Id"></div>
</div>
To match an element that has an attribute, simply attach the attribute selector directly without using :has()
.