CSCI-E3: Project Unit3a
Example for project unit3a.
by Larry Adams
HTML
<div id="swOpeningCrawl">
<p>It is a period of civil war. Rebel spaceships, striking from a hidden base, have won their first victory against the evil Galactic Empire.</p>
<p>During the battle, rebel spies managed to steal secret plans to the Empire's ultimate weapon, the DEATH STAR, an armored space station with enough power to destroy an entire planet.</p>
<p>Pursued by the Empire's sinister agents, Princess Leia races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the galaxy....</p>
</div>
<input type="button" id="transformButton" name="transformButton" value="Transform!" />
JavaScript
function transformText() {
// Get elements within the DIV tag
var theDiv = document.getElementById("swOpeningCrawl");
// While traversing the elements within the DIV tag...
for (var i=0; i < theDiv.children.length; i++) {
var el = theDiv.children[i];
// If the element is a 'p' element, grab its text
if (el.tagName === "P") {
// Save the text of the 'p' element
var text = el.childNodes[0].nodeValue;
console.log(text);
// Clear the contents of the 'p' element
el.innerHTML = '';
// Separate words into an array
var words = text.split(' ');
console.log(words);
// For each word in the text, add it to a new 'span' element
for (var j = 0; j < words.length; j++) {
var newSpan = document.createElement("SPAN");
var newText = document.createTextNode(words[j] + " ");
newSpan.appendChild(newText);
// Add an event handler to the 'span' element
newSpan.onclick = function () {
alert("The word we clicked on is '" + this.innerHTML + ".'");
};
// Append the 'span' element to the 'p' element
el.appendChild(newSpan);
}
}
// Continue traversing until we're done!
}
alert("Text transformed!");
}
document.getElementById("transformButton").onclick = transformText;