Java Reference
In-Depth Information
<script type=”text/javascript”>
var tdElement = document.getElementsByTagName(“td”).item(0);
tdElement.style.color = “red”;
</script>
</body>
</html>
If you ran this example, once again using the style object, it would alter the style of the contents of
the fi rst cell in the table. If you wanted to change the color of all the cells in this way, you could loop
through the node list, like this:
<script type=”text/javascript”>
var tdElements = document.getElementsByTagName(“td”);
var length = tdElements.length;
for (var i = 0; i < length; i++)
{
tdElements[i].style.color = “red”;
}
</script>
One thing to note about the getElementsByTagName() method is that it takes the element names
within quotation marks and without the angle brackets <> that normally surround tags.
Creating Elements and Text
The Document object also boasts some methods for creating elements and text, shown in the following table.
Methods of the Document Object
Description
createElement(elementName)
Creates an element node with the specifi ed tag name.
Returns the created element.
createTextNode(text)
Creates and returns a text node with the supplied text.
The following code demonstrates the use of these methods:
var pElement = document.createElement(“p”);
var text = document.createTextNode(“This is some text.”);
This code creates a <p/> element and stores its reference in the pElement variable. It then creates a text
node containing the text This is some text. and stores its reference in the text variable.
It's not enough to create nodes, however; you have to add them to the document. We'll discuss how to
do this in just a bit.
Property of the Document Object: Getting the Document's Root Element
You've now got a reference to individual elements on the page, but what about the tree structure men-
tioned earlier? The tree structure encompasses all the elements and nodes on the page and gives them
a hierarchical structure. If you want to reference that structure, you need a particular property of the
Search WWH ::




Custom Search