如何确定 JavaScript 中 HTML 元素的类型? [英] How can I determine the type of an HTML element in JavaScript?

查看:26
本文介绍了如何确定 JavaScript 中 HTML 元素的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一种方法来确定 JavaScript 中 HTML 元素的类型.它有 ID,但元素本身可以是

字段、
等.我怎样才能做到这一点?

解决方案

nodeName 是您要查找的属性.例如:

var elt = document.getElementById('foo');控制台日志(elt.nodeName);

注意 nodeName 返回大写且不带尖括号的元素名称,这意味着如果你想检查一个元素是否是

元素,你可以这样做:

elt.nodeName == "DIV"

虽然这不会给您预期的结果:

elt.nodeName == "

"

I need a way to determine the type of an HTML element in JavaScript. It has the ID, but the element itself could be a <div>, a <form> field, a <fieldset>, etc. How can I achieve this?

解决方案

nodeName is the attribute you are looking for. For example:

var elt = document.getElementById('foo');
console.log(elt.nodeName);

Note that nodeName returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div> element you could do it as follows:

elt.nodeName == "DIV"

While this would not give you the expected results:

elt.nodeName == "<div>"

这篇关于如何确定 JavaScript 中 HTML 元素的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆