Reputation: 1884
How to access href
attribute of parent anchor tag?
<a href="#"><li><div class="my-class">Click ME</div></li></a>
How do I change href value in jQuery?
I tried this,
$('.my-class').find('li').find('a').attr('href','http://example.com');
Upvotes: 1
Views: 68
Reputation: 10896
try something like this
$('.my-class').parent('a').attr('href','http://example.com');
REFERENCE
Upvotes: 2
Reputation: 56501
$('.my-class').find('li')
will be looking for li
element within the div.my-class
. Therefore it didn't worked.
Since a
is the parent of parent of the .my-class
element.
Then try this below code
$('.my-class').parents('a').attr('href','http://example.com');
or
$('.my-class').parent().parent().attr('href','http://example.com');
Upvotes: 1
Reputation: 4624
Try this
$('.myclass').parents('a').attr('href','http://example.com');
Hope this helps ,Thank you
Upvotes: 1
Reputation: 57105
Try .closest()
$('.my-class').closest('a').attr('href','http://example.com');
Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
Upvotes: 1
Reputation: 148110
You need to use closest() to get the ancestor, find is use to get descendants.
$('.my-class').cloest('a').attr('href','http://example.com');
Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree, reference.
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
Upvotes: 1
Reputation: 15699
Write:
$('.my-class').closest('a').attr('href','http://example.com');
closest()
traverses up through the DOM tree.
Upvotes: 1