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 via JavaScript (and other programming languages).
All HTML elements are defined as objects, and the programming interface consists of object methods and object properties.
Methods are actions you can perform (such as adding or modifying elements).
Properties are values you can get or set (such as the name or content of a node).
innerHTML Property
The simplest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
Example
The following code retrieves the innerHTML of a <p>
element with id="intro":
Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p id="intro">Hello World!</p>
<script>
var txt = document.getElementById("intro").innerHTML;
document.write(txt);
</script>
</body>
</html>
In the above example, getElementById is a method, and innerHTML is a property.
| | The innerHTML property can be used to get or change any HTML element, including <html>
and <body>
. |
| --- | --- |
The nodeName property specifies the name of the node.
- nodeName is read-only
- The nodeName of an element node is the same as the tag name
- The nodeName of an attribute node is the same as the attribute name
- The nodeName of a text node is always #text
- The nodeName of a document node is always #document
Note: nodeName always contains the uppercase tag name of the HTML element.
nodeValue Property
The nodeValue property specifies the value of the node.
- The nodeValue of an element node is undefined or null
- The nodeValue of a text node is the text itself
- The nodeValue of an attribute node is the attribute value
Getting the Value of an Element
The following example retrieves the text node value of a <p>
element with id="intro":
Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p id="intro">Hello World!</p>
<script>
var x = document.getElementById("intro");
document.write(x.firstChild.nodeValue);
</script>
</body>
</html>
nodeType Property
The nodeType property returns the type of the node. nodeType is read-only.
Some important node types include:
Element Type | NodeType |
---|---|
Element | 1 |
Attribute | 2 |
Text | 3 |
Comment | 8 |
Document | 9 |