DOM is an Application Programming Interface that has the properties and methods of every object.
Variables inside an object are called as Properties and Methods are the actions that an object does.
getElementById,getElementsByTagName and getElementByClassName are the three important methods and innerHTML is a property.
getElementById method is used to grab the elementID.
object.html
[html]
<!DOCTYPE html>
<html>
<head>
<title>Document Object MOdel</title>
<script type="text/javascript" src="jscode.js"></script>
</head>
<body>
<p id="para1">This is an example of DOM Method</p>
<button onclick="changeStyle()">Submit</button>
</body>
</html>
[/html]
jscode.js
[c]
function changeStyle()
{
var text = document.getElementById("para1").style.backgroundColor= "cyan";
}
[/c]
Output: When the Submit button is clicked, the following output appears.
In the above example, elementID is given as "para1". When the JavaScript encounters this ID, it is parsed by the "getElementById" to assign the property "backgroundColor" to the id text using the "style" object.
getElementByTagName method is used to grab the elements tag. This method builds a node list to differentiate the elements by giving the index. Below is an example.
object.html
[html]
<!DOCTYPE html>
<html>
<head>
<title>Document Object MOdel</title>
<script type="text/javascript" src="jscode.js"></script>
</head>
<body>
<p id="para1">This is an example of DOM Method</p>
<p id="para2">This is an example of DOM Method</p>
<button onclick="changeStyle()">Submit</button>
</body>
</html>
[/html]
jscode.js
[c]
function changeStyle() {
var paragraph = document.getElementsByTagName("p");
var changeParaText = paragraph[0].style.fontStyle = "italic";
var changeParaText = paragraph[1].style.fontStyle = "normal";
}
[/c]
Output: The below output appears when the submit button is clicked.
In the above example, a node list with two nodes are created for paragraph and the elements are grabbed by the tag name<p>
getElementsByClassName is used to select the elements by class name. This method also creates the node list similar to getElementsByTagName() method.
object.html
[html]
<!DOCTYPE html>
<html>
<head>
<title>Document Object MOdel</title>
<script type="text/javascript" src="jscode.js"></script>
</head>
<body>
<p class="para">This is an example of DOM Method</p>
<p class="para">This is an example of DOM Method</p>
<button onclick="changeStyle()">Submit</button>
</body>
</html>
[/html]
jscode.js
[c]
function changeStyle() {
var paragraph = document.getElementsByTagName("p");
var changeText = paragraph[0].style.color = "red";
var changeText = paragraph[1].style.color = "cyan";
}[/c]
Output: After clicking submit button, the following output appears: