Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What helps me make sense of it is that attributes in the narrowest sense are DOM nodes (Attr nodes). They can have properties (such as `name`, `value`, `ownerElement`, `prefix`), and collectively (as a NamedNodeMap, not an array) they can be accessed as the value of the `attributes` property of the element that owns them.

So in a sense the name of getAttribute(name) is misleading: it's probably better renamed getAttributeValue(name), because it doesn't really return an attribute (in the sense of an Attr node), but the value of the `value` property of the attribute node (owned by the element on which it is called) whose name is `name`.

See:

https://developer.mozilla.org/en-US/docs/Web/API/Element/get...

https://developer.mozilla.org/en-US/docs/Web/API/Element/get...

https://developer.mozilla.org/en-US/docs/Web/API/Attr



That's all true, but is there anything practical you can do with an attribute node, and el.attributes, that you can't do with setAttribute/getAttribute/getAttributeNames/hasAttribute?

You can't even move attribute nodes between elements. You can't event reorder attribute nodes within an element.


Not that I know of! It's just a way to help myself keep the distinction straight mentally. If at the back of my head I always think of attributes as DOM nodes in their own right, I'm much less tempted to infer from a DOM element having a particular attribute to it possessing a particular property, and vice versa.


Work with attributes whose name doesn't match the XML Name production.

That can be a real concern in some cases (it came up recently in the context of "how do I move all the attributes on node A to node B, given that node A's attributes can be anything that can be created by the HTML parser?" c.f. https://software.hixie.ch/utilities/js/live-dom-viewer/?save... )


Hah, good insight! I didn't realise you could move attributes either. I tried, but seems (unlike nodes) you need to remove them before adding them.


Look at the DOM Attr interface [1].

You can list attributes, get their name, namespace, value.

[1] https://developer.mozilla.org/en-US/docs/Web/API/Attr


All of which you can do with the other methods.


Sure


why do you care what order the attributes are in that you feel not being able to reorder them is a negative?


I don't. I was just trying to think of anything an iterable might offer over the other methods.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: