In firebug console 10 paragraphs is displayed in the source code of the page, but only the first one contains text.
It looks like the loop inserted the text each time into the same paragraph, overwriting it's value. How to insert the text into each paragraph?
(function(){
var names = ["Yaakov", "John", "Jen", "Jason", "Paul",
"Frank", "Larry", "Paula", "Laura", "Jim"];
for (var name in names) {
var new_par = document.createElement("p");
new_par.id = "new_par";
var greeter = document.getElementById("greeter");
greeter.appendChild(new_par);
var firstChar = names[name].charAt(0).toLowerCase();
if (firstChar === 'j') {
//byeSpeaker.speak(names[name]);
document.getElementById("new_par").innerHTML = "Goodbye" + " " + names[name];
} else {
//helloSpeaker.speak(names[name]);
document.getElementById("new_par").innerHTML = "Hello" + " " + names[name];
}
}
})();
Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Module 4 Solution Starter</title>
</head>
<body>
<h1>Module 4 Solution Starter</h1>
<div id="greeter"></div>
<script src="SpeakHello.js"></script>
<script src="SpeakGoodBye.js"></script>
<script src="script.js"></script>
</body>
</html>
The problem is that you are creating ten nodes with the same id, new_par, so you are always getting a reference to the first #new_par when you do
document.getElementById("new_par").innerHTML
The simplest solution will be to use the reference you already have, no need to call getElementById.
new_par.innerHTML = ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With