确定 Javascript 中元素的类型
我有这样的代码:
varparent = links[i].parentNode;
我想写一些类似的内容:
if (parent.typeOfElement == "div") {
...
}
我该怎么做?
I have this code:
var parent = links[i].parentNode;
I'd like to write something like:
if (parent.typeOfElement == "div") {
...
}
How can I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
.tagName
,这是(对于元素)与.nodeName
相同。所以:
请注意,对于 HTML,标签名称应该以大写形式返回,但在 XML(包括 xhtml)中,它应该保留原始大小写 - 对于 xhtml 意味着它应该是小写的。为了安全起见,并允许将来对文档类型进行任何更改,并允许非标准浏览器行为,您可能希望转换为全部大写或全部小写:
根据我的经验,
.tagName
使用得更多经常,但我认为有些人认为.nodeName
是更好的选择< /a> 因为它适用于属性(并且更多)以及元素。You can use
.tagName
, which is (for elements) the same as.nodeName
.So:
Note that the tag name is supposed to be returned in uppercase for HTML, but in XML (including xhtml) it is supposed to preserve the original case - which for xhtml means it should be lowercase. To be safe, and allow for any future changes to your document type and allow for non-standard browser behaviour you might want to convert to all upper or all lower:
In my experience
.tagName
is used much more often, but I gather that some consider.nodeName
a better choice because it works for attributes (and more) as well as elements.请参阅:http://www.javascriptkit.com/domref/elementproperties.shtml
See: http://www.javascriptkit.com/domref/elementproperties.shtml