3

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');
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Blake Rivell
  • 13,105
  • 31
  • 115
  • 231

1 Answers1

7

You 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().

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Thanks this worked perfectly. As you said .data() and .attr() both work. The only difference is .data() returns the actual number and .attr returns it as a string. – Blake Rivell Jul 09 '17 at 17:06
  • @Blake Rivell: Ah, fair enough. I forgot that .data() performs type conversions. – BoltClock Jul 09 '17 at 17:08
  • I actually just realized my main problem was that in my actual code I was using the name data-customerId instead of data-id. It seems that capital letters dont work with data attribute. Were you aware of this? – Blake Rivell Jul 09 '17 at 17:17
  • @Blake Rivell: I wasn't. Searching turned up [this](https://stackoverflow.com/questions/17351282/jquery-cant-get-data-attribute-value/17351380#17351380), which adds that this behavior is specific to .data(). – BoltClock Jul 09 '17 at 17:30