Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML DOM element name as a string

Suppose I have the following HTML snippet:

<input type="text" id="myinput" />

Now I want to get that DOM element using JavaScript:

var element = document.getElementById("myinput");

Works fine, no problem so far.

But when I print it inside an alert box using alert(element);, it displays object HTMLInputElement.
Is there a way to get that element name (HTMLInputElement) as a string?

(Notice that when saying "element name" I do not mean the name attribute of an element, but the name how it is displayed when using alert() for example, as described above.

like image 934
MC Emperor Avatar asked Mar 27 '26 09:03

MC Emperor


1 Answers

In some browsers, such as Firefox (and Chrome, potentially others) you can do:

element.constructor.name; // => "HTMLInputElement"

But in general it's a bit more complicated, perhaps not even totally reliable. The easiest way might be as such:

function getClassName(o) {
  // TODO: a better regex for all browsers...
  var m = (o).toString().match(/\[object (.*?)\]/);
  return (m) ? m[1] : typeof o;
}
getClassName(element); // => "HTMLInputElement"
getClassName(123); // => "number"

[Edit]

Or, using the "nodeName" attribute, you could write a utility function which should be generally much more reliable:

function getHtmlElementClassName(htmlElement) {
  var n = htmlElement.nodeName;
  if (n.matches(/^H(\d)$/)) {
    return "HTMLHeadingElement";
  } else if (/* other exceptional cases? */) {
    // ...
  } else {
    return "HTML" + n.charAt(0) + n.substr(1).toLowerCase() + "Element";
  }
}

(Thanks @Esailija for the smarter implementation, @Alohci for pointing out exceptional cases.)

like image 144
maerics Avatar answered Mar 29 '26 21:03

maerics