HTML Dom Tutorial
HTML DOM is an acronym that means HyperText Markup Language Document Object Model. This describes the hierarchy of the HTML Document object and all of the objects and methods within it. Using this concept within a scripting language, such as JavaScript, creates Dynamic HTML, or DHTML. DHTML is when JavaScript is used to alter elements within the HTML DOM.
Instructions
-
-
1
Write some HTML with an element identified by its id attribute for DOM access later.
<html>
<head>
<title>HTML DOM Tutorial</title>
</head>
<body>
<div id="myDiv">contents of div</div>
outside of div
</body>
</html>
You will use the HTML DOM to access the <div> element we just created.
-
2
Insert JavaScript into the <head> element of your HTML document. This one will point the variable "myElement" to the first HTML element with the "id" attribute set to "myDiv," and should work in almost every web browser.
<script type="text/javascript">
myElement = document.getElementById("myDiv");
</script>
To retrieve an array of HTML elements, you could instead use the less supported methods getElementsByTagName or getElementsByClassName. Refer to the Resources section for further reading on these methods.
-
-
3
Manipulate attributes of the HTML element to make DHTML.
myElement.innerHTML = "new contents of div";
myElement.style.backgroundColor = "red";
These two lines of JavaScript will change the contents of myDiv to the new text, and then change the background color of myDiv to red.
-
1
Tips & Warnings
These are the steps for implementing the HTML DOM in JavaScript. For a full reference of HTML DOM objects and methods, use the links in the References and Resources sections.
References
Resources
- Photo Credit Nick Koudis/Photodisc/Getty Images