HTML and CSS Reference
In-Depth Information
Dynamic IDs and Object Collections
In programs involving object collections, it can be important to know the position of
each document object within its collection. For example, in an object collection of list
items, does a particular list item represent the first li element found in the document,
or the second or the last? There is no property that provides this information, but you
can add an id attribute to mark each element. For example, the following code creates
an id attribute for each list item in the document; the id value is based on the location
of the list item in the collection:
var allListItems = document.getElementsByTagName(“li”);
for (var i = 0; i < allListItems.length; i++) {
allListItems[i].id = i + “listItemNumber”;
The first list item will have the id 0listItemNumber , the second list item will be marked
with the id 1listItemNumber , and so forth. To extract the index number from the id, you
would use the parseInt() function, which extracts the leading integer value from the
text string and ignores the remaining text. Thus, the first list item would return the index
value 0, the second would return the index value 1, and so forth.
There are several caveats. You must place the index number as the first character or
characters in the id, and the element must not already have an id attribute or else your
code will overwrite it. Your program cannot create new list items because this would
cause the index numbers not to match up with the revised document. Finally, your
dynamic id text string must not conflict with any other ids used with other elements in
the document, so it's a good idea to pick a pattern that is long and unusual.
JavaScript does provide other, perhaps more efficient, methods to keep track of the
position of an element within its object collection. One of these involves object nodes—a
topic you'll explore in the next tutorial.
Creating Object Collections Using CSS
Your next task for Rebecca's puzzle app is to hide the puzzle solution from the user.
Rebecca wants you to do this by changing the background color of every table data cell to
gold. The hanjie puzzle has been written to a Web table with the id hanjieGrid . So if you
were going to make this change using only CSS, you could apply the following style rule:
#hanjieGrid td {
background-color: rgb(233, 207, 29);
One way to accomplish the same thing in JavaScript is to first select the elements to be
changed using the querySelectorAll() method
document.querySelectorAll( selector )
which creates an object collection consisting of all the Web page objects that match the
CSS selector pattern selector . Thus, the following statement creates an object collec-
tion consisting of all of the table data cells in the hanjieGrid Web table:
var puzzleCells = document.querySelectorAll(“#hanjieGrid td”);
Search WWH ::

Custom Search