What am I doing wrong since it doesn't insert the text and only '[object Text]' appears, I already tried changing innerHTML to appendChild but it still doesn't work
function myFunction() {
var text = document.createTextNode("added text");
document.getElementById("text").innerHTML = text;
}
<button onclick="myFunction()">ADD TEXT</button>
<span id="text"></span>
The difference between
.appendChild(node);
and.innerHTML = htmlCode;
appendChild
Usage example:
innerHTML
Usage example:
Response:
After having this clear, you have tried a merger of both, you have commented that it does not work either by changing
innerHTML
toappendChild
, to which I suppose that your mistake has been to do.appendChild = text;
instead of.appendChild(text);
. Recommendation to the use oftextContent
beforeinnerHTML
orinnerText
, explanation at the bottom.Additional Information:
innerText VS innerHTML
innerText
it is better regarding security, it does not edit the html as such.Source: innerText vs innerHTML
innerHTML
it is better in performance (despite the fact that itinnerHTML
has to parse the HTML),innerText
it cares about the style of the text so it may take longer.Source: Performance innerText vs innerHTML
textContent
it is ALWAYS better , in terms of performance because it doesn't care about the style nor does it have to parse HTML, and in terms of security because it doesn't edit the HTML either.Delete this line
document.createTextNode
, below I leave the example