12 ms·
HTML Attributes vs. DOM Properties
- kristopolous 3y ago[flagged]
- rk06 3y agoAverage js developer thinks that react invented className and htmlFor
- cush 3y agoThe DOM is bad and knowing browser quirks probably isn’t the thing I’d gatekeep a junior engineer about
- chipdart 3y agoI think the average frontend developer doesn't care anymore because they only have to care about relevant things, and this ain't it.
- athrowaway3z 3y agoIt might be more useful to ask it the other way around. When and where would the average js developer learn this?
- Repulsion9513 3y agoWhy would you ever want to write data on an element as a property instead of an attribute? Yikes.
- deleted 3y ago[deleted]
- kcrwfrd_ 3y agoWhen you don’t want it coerced into a string?
- berkes 3y agoFor primitive types, serde isn't hard. It could even be part of a simple spec. Numbers, Dates, String[], Number[], Date[]. Edit: Or it could just be JSON. For complex types it is. But why and when do you need to store complex types in the DOM? Isn't that always a bad idea? I'm a seasoned web dev, but haven't been working on complex frontend apps, because I believe complexity and frontend web don't go together. So I may very well miss some use-cases.
- bryancoxwell 3y agoFor custom elements you may want to store data or methods that modify the element’s behavior.
- berkes 3y agoMethods as in callbacks? So, code? Do you then store a closure or such? Or a pointer to one (i.e. the function/name)? And how or what data would modify behaviour? As said: I'm unfamiliar with these concepts as I actively try to avoid them :)
- rado 3y agoWhen there is no need to appear in the HTML
- jraph 3y agoYour sentence can be understood in two ways, I'll answer the question "Why use domElement.attrname instead of the corresponding domElement.setAttribute('attrname') and domElement.getAttribute('attrname')?". It can look cleaner (matter of taste). It looks like a native JS assignment, and it's shorter. For open and hidden, it's way more intuitive and convenient to set and get booleans than testing the existence of the corresponding HTML attribute (Still not a fan of this thing, years after having learned this). (but maybe you meant "Why use domElement.randomprop instead of something like domElement.dataset.randomprop"?)
- sir_pepe 3y agoWhen you want to pass an object to a web component without going through JSON or some other stringification procedure.
- politelemon 3y agoHow do you read it in the web component afterwards? Passing it via property sounds quite useful.
- throwitaway1123 3y agoWeb components are implemented using custom elements which are just plain JS classes that extend the HTMLElement class, so you would access the property the same way you would access a property in a normal JS class.
- jaffathecake 3y agoThe author of the thread is arguing against properties.
- throwitaway1123 3y agoYes, I know. I wasn't making a prescriptive comment about whether or not developers should use properties, I was just making a descriptive comment about how properties are accessed in a web component to answer the specific question politelemon asked.
- politelemon 3y agoThanks understood, that makes it quite simple and intuitive thinking about it.
- jaffathecake 3y agoEvent listeners? Image data?
- 3y ago
- shunia_huang 3y agoI believe it's quite useful for framework developers for not required to build an abstract layer upon the already-exist-and-well-designed DOM layer to manage the state transitions or event handlings or something similar, you can't do too much if you are constrained to use only string values to encode/decode the inner state/data on the DOM.
- mg 3y agoThe gist of it seems to be that attributes sometimes behave like properties. Setting 3 attributes on an html element: <input id=good x=morning value=hn> Then logging 3 properties with the same names: <script> e = document.querySelector('input'); console.log(e.id); console.log(e.x); console.log(e.value); </script> Will output good undefined hn I'm not sure why. The article says it's because "Element has an id getter & setter that 'reflects' the id attribute". Which sounds logical. But MDN does not mention a getter function for "value" for example: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#value https://developer.mozilla.org/en-US/docs/Web/HTML/Element/in... It even calls "value" a property AND an attribute: "...access the respective HTMLInputElement object's value property. The value attribute is always..." And HTMLInputElement lists "value" under "properties": https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputEl... So maybe it's not as easy. Maybe <element some=thing> sometimes sets a property and sometimes sets an attribute.
- lgrapenthin 3y agovalue is a property and an attribute. Your x is only an attribute.
- jraph 3y agoIt's a matter of getters and setters being defined for well-known attributes on the DOM element indeed. This is why it doesn't work of 'x', the 'x' HTML attribute doesn't have a getter and a setter defined on the 'x' property of the DOM element (You can try defining custom getters and setters with defineProperty that call getAttribute and setAttribute if you want to experiment - I haven't experimented but I expect this to work and I think that's how predefined properties work). For 'value', MDN says: > it can be altered or retrieved at any time using JavaScript to access the respective HTMLInputElement object's value property While it doesn't say it is implemented using a setter and a getter (I suspect because it doesn't need to go into such details that are confusing if you don't know this mechanism), I think this is what it implies. I believe this can be found in the spec of the Javascript implementation of DOM. So it is as "easy" as it looks (note my phrasing totally allows you to find it looks difficult): for well-known HTML attributes, there are usually getters and setters for the corresponding DOM property. Usually, it's the same string, sometimes there's a conversion, for instance with booleans (for the open and the hidden attributes).
- jraph 3y agoInteresting article. I had built the right intuitions empirically (except for frameworks, which I don't practice much) but it's nice to read it. > The funny thing is, React popularised using className instead of class in what looks like an attribute. But, even though you're using the property name rather than the attribute name, React will set the class attribute under the hood. Yeah, I never understood why they did this. className in their XML-like syntax is ugly and it doesn't seem like they needed to do this. They could have gone with class. They are parsing this with their custom JSX parser, and these things are not JS identifiers. IIRC you need to use {accolades} to put JS expressions (objects) there.
- vaylian 3y agoGood article. There is also a nice middle ground with the data-attributes: ``` <div id="myDiv" data-payload="something"></div> ``` These data-attributes are then automatically available to JavaScript as a read+write property: ``` document.getElementById('myDiv').dataset.payload == "something" ``` However, one has to be mindful that HTML attributes use -kebab-case- while JavaScript uses camelCase. Thus ``` <div id="example-div" data-my-cool-data-attribute="fun"></div> ``` becomes ``` document.getElementById('example-div').dataset.myCoolDataAttribute == "fun" ```
- klysm 3y agoThese are also accessible to a degree from css
- vaylian 3y agoCool! What is the syntax for that?
- domgor 3y agoAttributes can be used in selectors like this `div[data-my-data="stuff"]`.
- wildrhythms 3y agoCSS is very powerful here because you can take advantage of the other attribute selectors to find partial matches: div[data-my-data^="my-prefix"] (selects by prefix) div[data-my-data$="my-suffix"] (selects by suffix) div[data-my-data*="my-substring"] (selects by substring) Quite a few more of these: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors#syntax https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_s...
- LorenzA 3y agoattr() can also be used to some degree https://developer.mozilla.org/en-US/docs/Web/CSS/attr https://developer.mozilla.org/en-US/docs/Web/CSS/attr
- fregante 3y agoThis is a good read for JS developers. TL;DR: they’re not the same thing. Only sometimes they match (e.g. `id`) but often they don’t. Something fun: JSX does not use attributes, even if they look like it. That’s why they have unusual naming/formatting (`htmlFor` and `className`)
- grose 3y agoGreat article. Maybe a hot take but I think it's a good thing that dialog and details modify the DOM. It allows for UI state to be serialized and stored in a native way. I think input.value should work the same way too (although it's probably too late for that). Consider how some browsers will remember what you input into forms when you hit the back button: I think representing this as a cached version of the modified DOM makes a lot more sense than whatever magic browsers currently use to remember it. Many CSS pseudoclasses like :checked feel like a pre-attribute-selector bandaid.
- jaffathecake 3y agoYeah, I get your point. On the other hand, I prefer the serialisation of the light DOM to reflect only changes I've made as the author. The serialisation isn't expected to represent page state. Imagine how that would work with <canvas>, or even things like event listeners.
- somishere 3y agoTend to agree ... with the added reflection that to a stylesheet, the DOM is the only worldview. Attributes - and the currently limited set of pseudo classes - afford its agency. If pseudos were extended to include all property state, DOM serialised or not, then we'd be onto something.
- shiomiru 3y ago> Consider how some browsers will remember what you input into forms when you hit the back button: I think representing this as a cached version of the modified DOM makes a lot more sense than whatever magic browsers currently use to remember it. That would not work either: > A control's value is its internal state. As such, it might not match the user's current input. > For instance, if a user enters the word "three" into a numeric field that expects digits, the user's input would be the string "three" but the control's value would remain unchanged. Or, if a user enters the email address " awesome@example.com" (with leading whitespace) into an email field, the user's input would be the string " awesome@example.com" but the browser's UI for email fields might translate that into a value of "awesome@example.com" (without the leading whitespace). From the standard: https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#a-form-control's-value https://html.spec.whatwg.org/multipage/form-control-infrastr...
- rmetzler 3y agoLOL, I feel like the author mix up the two things even in the title. There are HTML attributes, there is the DOM API (which for example exists also in other languages, but not always refers to HTML but mostly XML instead) and there are JavaScript Object properties. And because the DOM api uses JavaScript objects you can access properties. But only attributes are serialized / deserialised. And some frameworks blur this, so you get and set both as a „convenience“.
- jaffathecake 3y agoI know they're two different things. I wouldn't bother writing an article comparing two things that are the same, even though it wouldn't take long.
- rmetzler 3y agoApparently I worded my first sentence wrong and you didn't bother to read longer than that. Apologies. I just want to reiterate: DOM objects do have properties, because they are JavaScript objects. You make it sound like they have properties because this is something the DOM API set. And unfortunately this is only the case for some special HTML attributes, not for all of them.
- jaffathecake 3y agoI think you missed a couple of bits in the article: > the above only works because Element has an id getter & setter that 'reflects' the id attribute … It didn't work in the example at the start of the article, because foo isn't a spec-defined attribute, so there isn't a spec-defined foo property that reflects it. This is where the distinction is made between merely setting a property on a JavaScript object, and cases where you're actually calling an HTML-spec'd getter that has side effects. The whole "reflection" section of the article is dedicated to how these HTML-spec'd getters and setters change the behaviour from the basic JavaScript property operations shown at the start of the article, and how it differs from property to property. "LOL", I suppose.
- aixpert 3y agoso always use getProperty instead of getAttribute to avoid surprises?
- jaffathecake 3y agoNope, just el.propertyName. el.getProperty isn't a thing.
- clementmas 3y agoI understand the argument against updating the <dialog open> property but it's useful to be able to target it with CSS
- jaffathecake 3y agoThat's why I said it should also have a pseudo class. Similar to :checked on inputs.
- Kailhus 3y agoThat’s my case across all others too, so much eassier to debut by checking the dom in an instant rather go through the debugger process
- ale42 3y agoNice to see this well explained with examples, it can for sure benefit many people, especially that there are several details that are sometimes overlooked.
- londons_explore 3y agoAnd all of the things in this article represent complexity and behaviours that don't add anything to anyone's lives. This behaviour is all downside and no upside. The spec should have simply defined a dom object and a javascript object to be one and the same, with attributes and properties being the same thing.
- skrebbel 3y agoI agree, except with the “simply” part. This is not simple at all, unless you also demand that every property can only ever be a string. Otherwise, you need to think of conversions (eg from and to numbers), and what about properties that can be set to objects? Or properies that don’t correspond to attributes at all? I agree that any sort of convention/rule here that’d be 100% fixed would’ve been better, but it wouldn’t be simple.
- londons_explore 3y agothink the other way round... allow DOM attribute values to be of any javascript type... Sure, they maybe can't be serialized, but that isn't an issue.
- strix_varius 3y agoThat doesn't make any sense. DOM attributes are serialized as a fundamental part of their expression.
- layer8 3y agoSo is JavaScript. Granted, it would be more straightforward if it were a Lisp.
- afavour 3y agoIn what way is that not an issue? What happens when you use .outerHTML to get a string representation of the element? Not to mention that, unavoidably, the entire page HTML arrives to the browser as a string.
- keepamovin 3y agoDOM properties also known as IDL attributes
- jaffathecake 3y agoYeah, I deliberately avoided that terminology because few people outside of spec authors call them IDL attributes, and calling both things attributes is very confusing.
- keepamovin 3y agoHeh, I guess I’m a stickler for the textbook. Always have been hahaha :)
- lloydatkinson 3y agoReason #231 why web components are something of a nightmare.
- strix_varius 3y agoThis has nothing to do with web components. This is the behavior of built in HTML elements: https://developer.mozilla.org/en-US/docs/Glossary/IDL#content_versus_idl_attributes https://developer.mozilla.org/en-US/docs/Glossary/IDL#conten... If anything, web components make this behavior easier to control. They represent the ground truth rather than providing a leaky abstraction. The article demonstrates this in several places.
- kaoD 3y agoWell it has something to do: this complexity comes up front-and-center when writing Web Components (or rather, custom elements), where you often would want to pass around JS values seamlessly like in e.g. React props. Since custom elements are still in the regular DOM you have to deal with this soon enough that writing a custom element is likely the time you'd learn about this. And then you have to write many lines to deal with the impedance mismatch while you wouldn't in any component framework, including ensuring that both are synced in whatever form of serialization you come up with -- which ends up being an even greater mess usually... not to mention you also pay the de/serialization costs if you want to keep a real sync between them. As you can see I have written more `attributeChangedCallback`s and property proxies than I'd like (which is zero).
- lloydatkinson 3y agoThank you for writing this, it was frustrating reading their reply stating "this has nothing to do with web components" as if I was just making things up for fun.
- amortka 3y agowell explained, good read.
- aragonite 3y agoWhat 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/getAttributeNode https://developer.mozilla.org/en-US/docs/Web/API/Element/get... https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute https://developer.mozilla.org/en-US/docs/Web/API/Element/get... https://developer.mozilla.org/en-US/docs/Web/API/Attr https://developer.mozilla.org/en-US/docs/Web/API/Attr
- jaffathecake 3y agoThat'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.
- aragonite 3y agoNot 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.
- dylan604 3y agowhy do you care what order the attributes are in that you feel not being able to reorder them is a negative?
- deleted 3y ago[deleted]
- Waterluvian 3y agoFascinating article. I had always perceived DOM elements in JavaScript as proxies. They let you do things to that DOM element, but it’s still just a javascript object that you can assign to and do whatever, in addition to using the functions for interacting with the actual element.
- notnullorvoid 3y agoNice article, makes me wonder what a better representation would look like. It would be interesting if Html could have non string attributes that reference some local values from a scoped script tag or something. I found the take on attributes for default configuration to be an odd take. Think about "class" attribute for example. If it only ever showed the default, toggling classes would look really odd in the dom inspector / stringified html, either not showing an active class or showing an inactive one.
- jaffathecake 3y agoI didn't say it was for default configuration, just configuration. The class attribute works within this system. I, as the owner of the document, configure the class attribute. I can change its configuration over time, but only I do that. An alternative system would be where the browser adds and removes classes of its own, in response to things like hover/focus state. Thankfully it doesn't, and pseudo-classes are used instead.
- notnullorvoid 3y agoMy bad, that makes sense.
- assimpleaspossi 3y agoJake. Ahem: https://jakearchibald.com/2023/against-self-closing-tags-in-html/ https://jakearchibald.com/2023/against-self-closing-tags-in-...
- jaffathecake 3y ago> You'll see this syntax on my blog because it's what Prettier does, and I really like Prettier.
- assimpleaspossi 3y agoOne would think and hope that they would fix this mishandling when MDN, WHATWG and the W3C all complain online about Prettier.
- austin-cheney 3y agoPerhaps the most important difference is persistence, and isn’t covered by the article. Attributes are persistent for the duration that the same root object of the given DOM tree remains available for access, such as not leaving the page. Object properties only remain available until the given object is garbage collected.
- layer8 3y agoHow does that difference manifest?
- jaffathecake 3y agoThe object exists as long as the DOM node (the thing with the attributes) exists, so the lifecycle is the same. The DOM node could be cloned, or go through serialisation and deserialisation, in which case it's now a completely different DOM node (although with the same attributes), so it won't have the non-default properties of the other node.
- austin-cheney 3y agoNo. That is incorrect and makes assumptions not present. The DOM is a language agnostic tree model in memory. The DOM, or any node therein, is accessed via the DOM’s API. Accessing a single node in JavaScript generates a node object. That node object is an artifact in JavaScript language representing the DOM node at the moment of access. A DOM node is a living mutable thing, but the JavaScript object representing that node is not. It’s a static object in JavaScript language. That is also why a node list is not an array. The DOM is not an artifact of JavaScript. I can understand how this is confusing if you have never operated without a framework, but otherwise it’s really straightforward. This is one of the reasons I abandoned my JavaScript career. Nobody knows what the DOM is, which is their only compile target, and yet everyone wants to an expert.
- jaffathecake 3y agoWhat I said in my previous comment is observably true. Try making a demo where it isn't. > A DOM node is a living mutable thing, but the JavaScript object representing that node is not. The JavaScript object is mutable. The first example in the article shows this. > That is also why a node list is not an array. Modern APIs on the web return platform arrays (eg JavaScript arrays). https://webidl.spec.whatwg.org/#js-sequence https://webidl.spec.whatwg.org/#js-sequence - here's where the WebIDL spec specifies how to convert a sequence to a JavaScript array. I'm fully aware of NodeList. There's a reason the spec calls them "old-style" https://dom.spec.whatwg.org/#old-style-collections https://dom.spec.whatwg.org/#old-style-collections > I can understand how this is confusing if you have never operated without a framework, but otherwise it’s really straightforward Sighhhhhh. I've been a web developer for over 20 years, and spent a decade on the Chrome team working on web platform features. Most of my career has been on the low-level parts of the platform. Could it be possible that people are disagreeing with you, not because they're stupid, but because you're in the wrong? Please try to be open minded. Try creating some demos that test your opinions.
- throw156754228 3y agoThere's a Java script object behind each DOM node basically, that has extra stuff in it.
- deleted 3y ago[deleted]
- chrisjj 3y agoIt doesn't help that Google too is confused - and confusing. Search for 'html properties' gives results mostly about attributes.