HTML DOM attributes
Attributes are the values of nodes (HTML elements) that you can get or set.
Programming interface
The HTML DOM can be accessed through JavaScript (and other programming languages).
All HTML elements are defined as objects, and the programming interface is object methods and object properties.
Methods are actions you can perform (such as adding or modifying elements).
Attributes are values that you can get or set (such as the name or content of a node).
innerHTML property
The easiest way to get the content of an element is to use the innerHTML property.
The innerHTML attribute is useful for getting or replacing the content of an HTML element.
Example
The following code obtains the innerHTML of the <p> element with id="intro":
Example
<html><!DOCTYPE html> <html> <body> <p id="intro">Hello World!</p> <script> var txt=document.getElementById("intro").innerHTML; document.write(txt); </script> </body> </html>
Run Example»
Click the "Run Example" button to view the online example
In the above example, getElementById is a method, and innerHTML is a property.
The innerHTML attribute can be used to get or change any HTML element, including <html> and <body>. |
The nodeName attribute specifies the name of the node.
nodeName is read-only
The nodeName of the element node is the same as the label name
Attribute The nodeName of the node is the same as the attribute name
The nodeName of the text node is always #text
The nodeName of the document node is always #document
Note: nodeName always contains the tag name of the HTML element in uppercase letters.
nodeValue attribute
The nodeValue attribute specifies the value of the node.
The nodeValue of the element node is undefined or null
The nodeValue of the text node is the text itself
The nodeValue of the attribute node is the attribute value
Get the value of the element
The following example will retrieve the <p id="intro"> tag Text node value:
Instance
<html><!DOCTYPE html> <html> <body> <p id="intro">Hello World!</p> <script> x=document.getElementById("intro"); document.write(x.firstChild.nodeValue); </script> </body> </html>
Run Instance»
Click the "Run Instance" button to view the online instance
nodeType property
The nodeType property returns the type of node. nodeType is read-only.
The more important node types are:
Element type | NodeType |
---|---|
Element | 1 |
Attributes | 2 |
3 | |
8 | |
9 |