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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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: Ah, fair enough. I forgot that .data() performs type conversions.
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: I wasn't. Searching turned up this, which adds that this behavior is specific to .data().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.