DOM class property HTMLElement className when an element does not have a set of class names

When you have an HTML element without a set of class names, what is the value of the property of the HTMLElement class? My first thought was that it is undefined, but I found that in FF it is just an empty string. My question is: can I rely on this behavior in all current and future browsers? Is this part of any specification or is it just another browser trick to avoid errors in poorly written code?

+3
source share
2 answers

By default there will always be an empty string ( a DOMStringspecially ), and yes, you can rely on it without being null/ undefined.

The definition is really important here getAttribute():

Return Value DOMString
A value Attras a string or an empty string if this attribute does not have a specified or default value.

... it's really just an attribute that you throw back, so in both cases it is the same behavior, the interface just defines these attributes.

+4
source
interface HTMLElement : Element {
           attribute  DOMString            id;
           attribute  DOMString            title;
           attribute  DOMString            lang;
           attribute  DOMString            dir;
           attribute  DOMString            className;
};

- http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html

Also see the definition of DOMString .

So it should be safe.

+4
source

Source: https://habr.com/ru/post/1780240/


All Articles