The Document Object Model (DOM) is a platform-and-language-neutral interface that permits scripts to access and update the content, structure and style of the document. In theory every element of the web page can be dynamically updated in response to input from the user or other programs. HTML elements are treated as objects, their attributes are treated as properties of the objects. The DOM has a hierarchy of elements with the window as the top level object.
In JavaScript you translate this hierarchy into reference names which indicate the location of the element in the DOM. Generally, this is done by giving a tag an ID attribute. This id is used as the name of the object that is created in the browser when the page is displayed. While almost all tags in the page will create objects, we can most easily use the ones with names.
Many elements are be grouped into element collections which are arrays of all the elements of a particular type. For example, all the images in a document are grouped into an images collection that is part of the document object. If our image had a name, we could access it like this:
document.images["myImageID"].propertyto either examine or change a property. If we didn't give it a name but we knew it was the first image, we could use
document.images[0].propertyThis is most commonly used if we want to work on all the elements of a certain type.
In the bad old days (about 2 years ago), the major browsers used very different ways to access named elements. But the W3C (world web standards committee) developed a common method and all recent browsers support this. In here, we will use this method because it is simple and portable.
We will use the getElementByID(tagID) tool to access that element
document.getElementByID("myImage")
<p id="paraex">
Here is an example of how this can be used.
This paragraph is named "paraex" and we will find it and show the
text inside the paragraph while changing the text color to highlight it.
</p>
|
Here is an example of how this can be used. This paragraph is named "paraex" and we will find it and show the text inside the paragraph while changing the text color to highlight it. |
function showpara() { // first we find the paragraph and use the // obj variable to refer to it. var obj = document.getElementById("paraex"); /* in each paragraph object, there is a style object. This we can use to change the CSS properties of the object. Here we want to change the text color */ obj.style.color="red"; // Next we want to get the text that is inside the paragraph // This is in the innerHTML property of the object var text = obj.innerHTML; alert("The text of paraex is :" + text + ":"); // now change the text color back to black obj.style.color="black"; } // showpara |
<a href="#ex1" onClick="showpara();">click here</a>
click here.
|
There will be more examples of using the DOM as we go. The combination of HTML, CSS, JavaScript and the DOM give us very powerful control over the web page.