Tony Stark Tony Stark - 9 months ago 27
Javascript Question

adding content into existing element node, expecting the result to be `Region 6` but instead got 'Region<span>6</span>'

I'm new to javascript and is learning how to add new content into existing html. In the code below, i'm trying to count the number of

in the DOM and display the total number to an existing

I was expecting the result to be
Region 6
but instead I have got

enter image description here

Because I just started learning javascript, i'm not sure what i did wrong. Could someone please help me out? Thanks in advance for any suggestions!

enter image description here


This is because you used .textContent to set the text to "<span>" + totalItems + "</span>".

The docs for textContent state: "... the text is not parsed as HTML ... Moreover, this avoids an XSS attack vector.".

You might want to use .innerHTML instead, but be cautions as it can make your site vulnerable to cross-site scripting.