Why does tagName method in JavaScript return HTML tags in capital letters?

1k Views Asked by At

Why does tagName method in JavaScript return HTML tags in capital letters? HTML tags should be written in small letters.

3

There are 3 best solutions below

1
Rarblack On BEST ANSWER

The older versions of HTML back when JavaScript was first created used all caps for tag names by convention instead of today's lowercase. To stay backward-compatible with older code tagName() still returns all uppercase and has been stuck that way.

0
T.J. Crowder On

Because that's how tagName is defined:

The tagName attribute’s getter must return the context object’s HTML-uppercased qualified name.

HTML tag names (and attribute names) are not case sensitive, but the canonical version of the tag name is in all caps, regardless of how the HTML that created the element was written:

document.querySelectorAll("div").forEach(function(div) {
  console.log(div.tagName);
});
<div></div>
<DIV></DIV>
<Div></Div>

This is quite handy, since it means code looking at tagName doesn't have to worry about doing a case-insensitive comparison if it needs to know whether the tag matches a specific tag name. That is, if (element.tagName === "DIV") is reliable in HTML pages.

0
scraaappy On

To be complete, note that tagName:

Returns the tag name of the element on which it's called. For example, if the element is an , its tagName property is "IMG" (for HTML documents; it may be cased differently for XML/XHTML documents).

See result below with svg:

[...document.querySelectorAll("*")].forEach(function(el){
  console.log(el.tagName);
});
 <svg width="300px" height="300px" 
    xmlns="http://www.w3.org/2000/svg">
    <text x="10" y="50" font-size="30">My SVG</text>
  </svg>