简体   繁体   中英

Adding innerHTML using Javascript

<div id="ones">
 <span class="dice">&#9856;</span>
 <p>-</p>
 </div>

I am accessing this p tag in inside id=ones . By this Javascript line.

var valueCount = 0;
    var valueCount = document.getElementById('ones').getElementsByTagName('p').textContent;
    valueCount++;
    document.getElementById('ones').getElementsByTagName('p').textContent = valueCount;

on the console, I am getting NaN . Where am I doing wrong???

Instead of using document.getElementById for accessing p tag which doesn't have any id or class attribute.You can use document.querySelector but need a digit in the paragraph that can be converted to a number using for example parseInt

 const valueP = document.querySelector('#ones p'); var valueCount = parseInt(valueP.textContent); valueCount++; valueP.textContent = valueCount;
 <div id="ones"> <span class="dice">&#9856;</span> <p>0</p> </div>

in code you provided we can see that you define valueCount as 0, then we take text data from p tag and assign this value to valueCount so now in valueCount we have '-' string, then we try to increment this incorrect value, so now valueCount is NaN, that's the issue

var valueCount = 0;
var valueCount = document.getElementById('ones').getElementsByTagName('p').textContent;
valueCount++;
document.getElementById('ones').getElementsByTagName('p').textContent = valueCount;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM