Skip to Main Content
Head Rush Ajax
book

Head Rush Ajax

by Brett McLaughlin
March 2006
Beginner to intermediate content levelBeginner to intermediate
448 pages
13h 33m
English
O'Reilly Media, Inc.
Content preview from Head Rush Ajax
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()
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Reinventing the Organization for GenAI and LLMs

Reinventing the Organization for GenAI and LLMs

Ethan Mollick
Head First Ajax

Head First Ajax

Rebecca M. Riordan

Publisher Resources

ISBN: 0596102259Errata PageSupplemental Content