Java Reference
In-Depth Information
The second method, getElementsByTagName() , works in the same way, but, as its name implies,
it can return more than one element. If you were to go back to the example HTML document
with the table and use this method to return the table cells ( <td/> ) in your code, you would get
a node list containing a total of four tables. You'd still have only one object returned, but this
object would be a collection of elements. Remember that collections are array‐like structures,
so specify the index number for the specific element you want from the collection. You can use
the square brackets if you want; another alternative is to use the item() method of the NodeList
object, like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>This is a test page</title>
</head>
<body>
<span>Below is a table</span>
<table>
<tr>
<td>Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
</tr>
</table>
<script>
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 first 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>
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.
The third method, querySelector() , retrieves the first element that matches the provided CSS
selector. This is a convenient way of retrieving an element that does not have an id attribute (if it
does have an id attribute, you want to use getElementById() ).
Search WWH ::




Custom Search