tagName和nodeName的区别

来源:互联网 发布:淘宝商城货到付款童装 编辑:程序博客网 时间:2024/06/05 02:33

首先介绍DOM里常见的三种节点类型(总共有12种,如docment):元素节点,属性节点以及文本节点,例如<h2 class="title">head</h2>,其中h2是元素节点,class是属性节点,head是文本节点,在这里你可以说h2这个元素节点包含一个属性节点和一个文本节点。其实几乎所有HTML的标签都是元素节点,而id, title, class等则是属性节点,而元素所包含的文本内容则是文本节点。

tagName和nodeName的语义是一样的,都是返回所包含标签的名称,例如上面的h2标签,都是返回h2,但是tagName只能在元素标签上使用,而nodeName则可以在所有的节点上使用。下面是nodeName在不同节点上的值:

InterfacenodeNamenodeValueattributesAttrname of attributevalue of attributenullCDATASection#cdata-sectioncontent of the CDATA SectionnullComment#commentcontent of the commentnullDocument#documentnullnullDocumentFragment#document-fragmentnullnullDocumentTypedocument type namenullnullElementtag namenullNamedNodeMapEntityentity namenullnullEntityReferencename of entity referencednullnullNotationnotation namenullnullProcessingInstructiontargetentire content excluding the targetnullText#textcontent of the text nodenull

而tagName只有在元素节点上才会有值。

从DOM层次来看,nodeName是node接口上的property,而tagName是element接口上的property,所有的节点(元素节点,属性节点,文本节点等12种)都继承了node接口,而只有元素节点才继承了element节点,因此nodeName比tagName具有更大的使用范围。

总结:tagName只能用在元素节点上,而nodeName可以用在任何节点上,可以说nodeName涵盖了tagName,并且具有更多的功能,因此建议总是使用nodeName。