Should href be set with prop() or attr()? [duplicate]
Asked Answered
C

1

32

If I want to change the href of a link dynamically, should I do so using prop() or attr()?

Cupronickel answered 12/8, 2013 at 14:38 Comment(4)
It's not duplicate. The answer to that question isn't clear about things such as href. Please read both question and answer before going commando.Cupronickel
I hope people are aware that those "dupes" are 5 and 2 years old respectively... jQuery has changed since then, and neither are appropriateClaudelle
They are absolutely appropriate and relevant. The only deciding factor between using .attr and .prop are whether you want to modify the attribute or the property. The functionality of jQuery as far as .prop and .attr is now almost exactly as it was when 1.6.0 launched.Kerikeriann
The .prop() vs .attr() question brings up a good discussion on href specifically - shows that when you retrieve the href using prop, you get the full path, while attr gets you whatever you put in it, either in the markup, or if you assigned to it using javascript. Doesn't look like it matters for setting the value, but retrieving it definitely has differences.Mcilwain
C
26

You would use .attr(), as .prop() is more commonly used for boolean properties such as checked, selected, etc - though it is certainly possible with .prop it's arguably less clear as per your intent

Though I do believe that ultimately they are very similar (or used to be) functionality-wise

Just a note: the jQuery API site seems to follow the boolean 'sway':

.prop() - Examples use checked and disabled

.attr() - Examples use alt title and src

Claudelle answered 12/8, 2013 at 14:40 Comment(4)
@Cupronickel No worries - it'd be good if people read and understood the question before playing follow the leaderClaudelle
@Cupronickel Yea no worries - has to be 15 minutes I thinkClaudelle
I just hit a case today, in IE11, where I attempted to modify an external-link anchor on-the-fly using prop() and the link stopped opening in a new tab (in fact it stopped opening at all). You definitely should use attr only for href.Kirakiran
@GoneCoding ... when setting the url. For retrieving it, like @JoeEnos mentions in his comment on the question, .attr('href') will return the text value from the markup while .prop('href') will return an absolute URL (where applicable).Colver

© 2022 - 2024 — McMap. All rights reserved.