JS DOM: Node Name

By Xah Lee. Date: . Last updated: .
node.nodeName
  • Return the node's (tag) name (a string), if the node is a element node (nodeType is 1).
  • If it's a text node, the value is "#text".
  • For HTML document, the return value is usually all UPPER CASE. (regardless what's in the file.)
  • For XML/XHTML, it is always lowercase (because XML allow just lowercase.) However, there are edge cases, when a DOM element is imported from htm/html5/xml, or when older browser encounters a tag it doesn't know.

[see HTML: Case Sensitivity]

You can use str.toLowerCase() to convert it.

// create a paragraph element and insert it as first node of body
const xnew = document.createElement("p");
xnew.setAttribute("id", "WkHwq");
xnew.textContent = "good eve";
document.body.prepend(xnew);

// get the paragraph element
const xx = document.getElementById("WkHwq");

// paragraph element nodeName
console.log(xx.nodeName === "P");

// text node's nodeName
console.log(xx.firstChild.nodeName === "#text");