Complexity
Complexity

Reputation: 5820

jQuery - Set class on a parent element

Considering the following HTML:

<div class="icongroup inline">
  <a href="http://www.google.be">
    <div class="bigicon icon relative inline center disabled">
      <img id="delete" src="Resources/Icons/Delete.png" alt="Delete">
      <div class="iconlegend">Delete</div>
    </div>
  </a>
</div>

Now, I have a jQuery selector that takes the delete element:

var element = $("#delete");

And now I want to disable the anchor element that's somewhere above the element.

Current, I do use this code:

$(element).parent().parent().on("click", function(e) {
  e.preventDefault();
  return false;
})

That's working without an issue, but I was just wondering if there is a more cleaner solution to do this. Thus, not using the parent().parent()

Upvotes: 0

Views: 38

Answers (2)

David Thomas
David Thomas

Reputation: 253318

Sure:

element.closest('a').on("click", function(e) {
  e.preventDefault();
  return false;
});

It's worth noting that element is already a jQuery element, so you can chain jQuery methods to it directly, rather than re-wrapping with jQuery.

References:

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

Yep:

element.closest("a").on("click", function() {

Upvotes: 1

Related Questions