I frequently find myself wanting to refer to the contents of an element on a web page, having got hold of that element in the DOM. However, I equally frequently forget how to access this content.
The confusion arises because there are various ways to get hold of the content of an element:
innerHTML all seem to do the job in different circumstances. In the hope that I’m not the only one with this problem, I looked into the matter…
In a nutshell:
nodeValuereturns attributes or text (read/write)
valuereturns the text content of an attribute (read)
datais used to access text content of a node (read/write)
textContentreturns the text content of a node and its descendents (read/write)
innerTextreturns the text content of a node and its descendents (read/write)
innerHTMLreturns the HTML contained by an element (read/write)
nodeValue, counter-intuitively, does not return the text content of a node such as a paragraph i.e. it is not a W3C analogue of
nodeValue is in the DOM Core specification and is well supported by browers. It is a read/write attribute.
This table from developer.mozilla.org shows the return value of accessing nodeValue on various nodes:
|Attr||value of attribute|
|CDATASection||content of the CDATA Section|
|Comment||content of the comment|
|ProcessingInstruction||entire content excluding the target|
|Text||content of the text node|
value returns the text value of a node’s attribute. This does not work with text nodes.
value is in the DOM Core Specification and it is very poorly supported in Windows IE, although Firefox does support it. It is a read-only attribute.
data is used to address the content of a text node. It is the same as nodeValue for that node.
data is in the DOM Core Specification and it is well supported by browsers. It is a read/write attribute.
innerText returns the text contained in a node and its descendants, ignoring any contained tags. Whilst
textContent is in the DOM Level 3 Core Specification and it is not really supported at all except in Firefox,
innerText is well supported by browsers, the exception being buggy support in Mozilla 1.75. Both are read/write attributes.
innerHTML returns the markup contained in a node and its descendants. Whilst
innerHTML is not in a W3C specification, most browsers support it and it is often faster than W3C DOM methods. It is a read/write attribute.