MC Emperor
MC Emperor

Reputation: 22997

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.

Upvotes: 2

Views: 17656

Answers (5)

maerics
maerics

Reputation: 156434

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.)

Upvotes: 5

pete
pete

Reputation: 25081

document.getElementById returns the HTML element as an object. Simply get the attribute of the object you want to display in the alert instead (e.g., alert(element.getAttribute('ID'));). Alternatively, if you want '[object HTMLInputElement]' displayed in the alert, simply call the toString() method on the object in the alert (e.g., alert(element.toString());).

Hope this helps,

Pete

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

When passing an object to the alert() function, it implicitly calls .toString() on that object in order to get the text for the alert. You could do something like:

var element = document.getElementById("myInput");
var string = element.toString(); // this will return 'object HTMLInputElement'

then work with the string variable to get only the HTMLInputElement part.

Upvotes: 1

danyloid
danyloid

Reputation: 1677

if I've got the question correctly you should try document.getElementById("myinput").toString().

Upvotes: 0

greut
greut

Reputation: 4373

alert(element.nodeName);

https://developer.mozilla.org/En/DOM/Node.nodeName

Upvotes: 4

Related Questions