Reputation: 111
I have a javascript segment that prints output to a div.
output.textContent = "";
for(i=0; i<14; i++){
output.append(document.createElement("p").innerHTML = net_words(sonnet[i]));
output.append(document.createElement("br"));
}
The function net_words
that generates the output is as follows:
function net_words(line) {
var net_line = Math.floor(Math.random()*4)
var ret = ""
if (net_line != 1) {
ret += "<span class=\"netno\">"
ret += line
}
else {
var net_list = line.split(" ")
var rand_word = Math.floor(Math.random() * net_list.length)
ret += "<span class=\"netno\">"
for (var i=0; i<net_list.length; i++) {
if (i == rand_word) {
ret += "<span class=\"netyes\">"
ret += net_list[i]
ret += " "
ret += "</span>"
}
else {
ret += net_list[i]
ret += " "
}
}
}
ret += "</span>"
return ret
}
The problem is, it prints the line as follows:
<span class="netno">From fairest creatures we desire increase</span>
That is, it prints it with the HTML tag visible, rather than applied to the code. When I paste it into the text editor for stack overflow, it prints as normal (no tags) unless I put it as a code snippet. What is the cause of this error?
Upvotes: 1
Views: 439
Reputation: 18423
The problem is here:
output.append(document.createElement("p").innerHTML = net_words(sonnet[i]));
You think that you appended <p>
, but in fact you appended the result of the assignment. To fix it do:
var p = document.createElement("p");
p.innerHTML = net_words(sonnet[i]);
output.append(p);
or
output.innerHTML += '<p>' + net_words(sonnet[i]) + '</p>';
Upvotes: 1