266
Chapter 4.5
Create JS le Add CD to Top 5
Start over
Add CD rankings
I’ve been thinking about how we handle adding rankings to
the CDs... but we don’t keep up with how many CDs have
been added to the Top 5. So I think that’s what we need
to do rst. We can just count up the number of child
elements named “img” in the “top5” <div>, right?
function addToTop5() {
var imgElement = this;
var top5Element = document.getElementById(“top5”);
var numCDs = 0;
for (var i=0; i<top5Element.childNodes.length; i++) {
if (top5Element.childNodes[i].nodeName.toLowerCase() == “img”) {
numCDs = numCDs + 1;
}
}
/* Code to move a CD into the Top 5 listings is here */
}
And now that you know how to loop through an
element’s child nodes and how to gure out an
element’s name, this should be pretty easy.
Let’s add a new variable to our addToTop5()
function and set it to the number of CDs in the
top 5 listings:
Here’s the
new variable.
Start it
out at 0.
You need to check each child
element of the “top5” <div>.
We loop through the top5 <div>’s children, and
only count up <img> elements... remember, there
could be text nodes with just spaces in them, so
check each child to see if it’s an <img>.
Just bump the counter up
for each CD cover.
If you’re feeling unsure about looping and
checking an element’s name, peek back at
addOnClickHandlers() on page 254.
adding cd rankings
Exactly!