If I want to change the href of a link dynamically, should I do so using prop()
or attr()
?
Should href be set with prop() or attr()? [duplicate]
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
@Cupronickel No worries - it'd be good if people read and understood the question before playing follow the leader –
Claudelle
@Cupronickel Yea no worries - has to be 15 minutes I think –
Claudelle
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.
href
. Please read both question and answer before going commando. – Cupronickelhref
specifically - shows that when you retrieve thehref
usingprop
, you get the full path, whileattr
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