Similar Topic:
JavaScript setAttribute vs .attribute=
javascript dom, how to handle "special properties" as versus attributes?
On multiple occasions, I've encountered criticism in forums or Usenet about the way I access attributes in my code. Instead of using var link = a.href
, I've been advised to use
var link = a.getAttribute('href');
and setAttribute() for assignment. I usually brush it off, but now I'm curious about when it would be more appropriate to use one method over the other.
People claim that using
var link = a.getAttribute('href');
is the right approach, but no one explains why. So, I'm left wondering in which scenarios this method is preferable.
When should I opt for
var link = a.getAttribute('href');
instead of var link = a.href
?And when is it better to use setAttribute() instead of directly assigning a value to a member, like `a.href = 'someURL';