Introduction to DHTML
Dynamic HTML refers to the use of JavaScript to dynamically change the attributes, contents, and style rules of HTML elements, and even create new
elements. It is called dynamic because HTML can be changed on the fly without reloading the page. DHTML's true power lies in its ability to
access and manipulate styles such as position, visibility, and z-index. Imagine the possibilities.
When implementing DHTML, versatile div and span tags are used most often and are assigned an ID, class, or both.
<style>
#myPrettyDiv {
position:absolute; left:200px; top:200px;
width:300px; height:300px;
visibility:visible;
z-index:2;
background-color:#660099;
background-image: URL(../images/spacer.gif);
}
</style>
<div id="myPrettyDiv" class="prettyBackground"></div>
Gaining Access to Any Element with getElementById()
JavaScript provides easy access to any HTML element that has been assigned an ID. The
getElementById() method works simply and beautifully.
It takes a string argument which is the ID of the element you want access to. Watch the uppercase letters in this method and note the word
"Element" is singular.
<script>
document.getElementById("myPrettyDiv");
</script>
<div id="myPrettyDiv">
Gaining Access to Any Element with getElementsByClassName()
You also have access to elements through their class names with the method
getElementsByClassName(). This method also takes the class
attribute as a string for it's argument. Note the uppercase letters and the word "Elements" is plural this time.
<script>
document.getElementsByClassName("prettyBlue");
</script>
<div id="myPrettyDiv" class="prettyBlue">
If there is more than one element with the same ID or CLASS, these methods will return an array of every matching element.
More ways to Use getElementsByClassName()
You can specify a root element with which to search for a class name match. This way, you can find elements within certain other elements, instead
of matching throughout the entire document.
document.getElementById('myPretyDiv').getElementsByClassName('prettyBlue');
You can find more than one element at a time with getElementsByClassName():
document.getElementsByClassName('prettyBlue prettyPink');