Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
159
rated 0 times [  160] [ 1]  / answers: 1 / hits: 16893  / 13 Years ago, thu, january 12, 2012, 12:00:00

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.


More From » html

 Answers
29

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


[#88054] Wednesday, January 11, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darleneh

Total Points: 231
Total Questions: 110
Total Answers: 94

Location: Spain
Member since Thu, Dec 23, 2021
3 Years ago
darleneh questions
;