28

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

j08691
  • 190,436
  • 28
  • 232
  • 252
Francisc
  • 66,160
  • 57
  • 172
  • 264
  • 3
    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. – Francisc Aug 12 '13 at 14:45
  • I hope people are aware that those "dupes" are 5 and 2 years old respectively... jQuery has changed since then, and neither are appropriate – MDEV Aug 12 '13 at 14:48
  • 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. – Kevin B Aug 12 '13 at 14:50
  • 5
    The [.prop() vs .attr()](http://stackoverflow.com/questions/5874652/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. – Joe Enos Aug 12 '13 at 14:51

1 Answers1

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

MDEV
  • 10,240
  • 1
  • 29
  • 49
  • @Francisc No worries - it'd be good if people read and understood the question before playing follow the leader – MDEV Aug 12 '13 at 14:46
  • @Francisc Yea no worries - has to be 15 minutes I think – MDEV Aug 12 '13 at 14:49
  • 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`. – Gone Coding Mar 17 '16 at 14:36
  • @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). – Oliver Feb 06 '20 at 10:29