270
Chapter 4.5
Create JS le Add CD to Top 5
Start over
Add CD rankings
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;
}
}
if (numCDs >= 5) {
alert(“You already have 5 CDs. Click \”Start Over\” to try again.”);
return;
}
top5Element.appendChild(imgElement);
imgElement.onclick = null;
var newSpanElement = document.createElement(“span”);
newSpanElement.className = “rank”;
var newTextElement = document.createTextNode(numCDs + 1);
newSpanElement.appendChild(newTextElement);
top5Element.insertBefore(newSpanElement, imgElement);
}
Completing addToTop5()
Here’s the completed addToTop5() function. Make sure your answers match
ours, and then add all of this new code to top5.js.
Compare numCDs to 5 to
prevent too many CDs from
being added.
All the create methods
are available through the
document object.
This sets the
“className”
attribute of
the <span>.
The text node should have
the next CD ranking.
The <span> goes before this CD’s <img>
element, under the “top5” <div>.
Just stick the text
node at the end of
<span>’s child nodes list.
completing addToTop5()