Naveen Gamage
Naveen Gamage

Reputation: 1884

Accessing parent attributes

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

Answers (6)

rajesh kakawat
rajesh kakawat

Reputation: 10896

try something like this

 $('.my-class').parent('a').attr('href','http://example.com');

REFERENCE

http://api.jquery.com/parent/

Upvotes: 2

Praveen
Praveen

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

SarathSprakash
SarathSprakash

Reputation: 4624

Working DEMO

Try this

  $('.myclass').parents('a').attr('href','http://example.com');

Hope this helps ,Thank you

Upvotes: 1

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.

fiddle Demo

Upvotes: 1

Adil
Adil

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

closest()

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.

find()

Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

Upvotes: 1

codingrose
codingrose

Reputation: 15699

Write:

$('.my-class').closest('a').attr('href','http://example.com');

closest() traverses up through the DOM tree.

More information here.

Upvotes: 1

Related Questions