Alex Nowak Alex Nowak - 19 days ago 6
Javascript Question

The loop is supposed to create 10 paragraphs and insert text, but the text only appears in one

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>

Answer

The problem is that each paragraph has the same id. I added a counter variable, to add at the end of id...

(function(){
    var counter = 0;
    var names = ["Yaakov", "John", "Jen", "Jason", "Paul", 
        "Frank", "Larry", "Paula", "Laura", "Jim"];
    for (var name in names) {

        var new_par = document.createElement("p");
        var par_id = "new_par" + counter;
        new_par.id = par_id; 
        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(par_id).innerHTML = "Goodbye" + " " + names[name];

        } else {
            //helloSpeaker.speak(names[name]);
            document.getElementById(par_id).innerHTML = "Hello" + " " + names[name];         
    }
    counter++;
    }

})();