Reading at MDN about Element.tagName it states:
On HTML elements in DOM trees flagged as HTML documents, tagName returns the element name in the upper
tagName
and nodeName
comes in lowercase or case sensitive, in case page response headers is having Content-type: application/xhtml+xml;
header or any xhtml related content type.
e.g. document.documentElement.nodeName
returns html
Read this for more cases: https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-745549614
In WebKit/Chromium it is not trustable, WebKit can create tagName properties also in lowercase, most of web pages builds uppercase tagName's, but it is also possible to build lowercase values, so if you use WebKit you must be prepare to support both cases. I thought tagName's are allways uppercase(most of are) and I see I was wrong, now I must little fix my script :)
chrome's inspector screenshot here
EDIT: console.log
My tests show that the tagName
of SVG elements seems to be lowercase in all browsers I checked in August 2018 (Chrome 68, Firefox 61, Edge 42, IE11)
Not sure how that relates to the "DOM trees" mentioned in the MDN docs - maybe SVG trees are handled separately/differently despite of them being part of the DOM tree. In the end, developers do typically speak of "SVG elements" and "DOM elements", as in pointing out that they're not the same thing.
In any case, if your application needs to handle SVG elements as well as regular DOM elements, make sure to use tagName.toUpperCase()
.
Work with element.tagName.toLowerCase()
if your code requires the output in lower case. If the standards change in the future to lowercase then you would not get a different value in your output since it's formatted to lowercase anyway.
On the contrary, if you left it without toLowerCase()
then your code output can change if the standards are changed to output as lowercase.
I doubt the standard will change for this though. This is entirely up to your needs.
You don't have to toLowerCase
or whatever, browsers do hehave the same on this point (surprisingly huh?).
About the rationale, once I had discussion with a colleague who's very professional on W3C standards. One if his opinion is that using uppercase TAGNAME would be much easier to recognize them out of user content. That's quite persuasive for me.
Edit: As @adjenks says, XHTML doctype returns mixed-case tagName if the document is served as Content-Type: application/xhtml+xml
. Test page: http://programming.enthuses.me/tag-node-case.php?doc=x
Technically, please read this spec for more info: http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-745549614
Note that this (tagName) is case-preserving in XML, as are all of the operations of the DOM. The HTML DOM returns the tagName of an HTML element in the canonical uppercase form, regardless of the case in the source HTML document.
As of asker's question: this is trustable. Breaking change is not likely to happen in HTML spec.