tagName只能在元素标签上使用,而nodeName则可以在所有的节点上使用。
DOM中有12种节点类型,常见的有三种:元素节点,属性节点以及文本节点。
例如<h2 class="title">head</h2>,其中h2是元素节点,class是属性节点,head是文本节点。
下面是nodeName在不同节点上的值:
Interface | nodeName | nodeValue | attributes |
---|---|---|---|
Attr | name of attribute | value of attribute | null |
CDATASection | #cdata-section | content of the CDATA Section | null |
Comment | #comment | content of the comment | null |
Document | #document | null | null |
DocumentFragment | #document-fragment | null | null |
DocumentType | document type name | null | null |
Element | tag name | null | NamedNodeMap |
Entity | entity name | null | null |
EntityReference | name of entity referenced | null | null |
Notation | notation name | null | null |
ProcessingInstruction | target | entire content excluding the target | null |
Text | #text | content of the text node | null |
总结:tagName只能用在元素节点上,而nodeName可以用在任何节点上,可以说nodeName涵盖了tagName,并且具有更多的功能,因此建议总是使用nodeName。