0
<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???

1
  • Get Elements By Tag Name. Elements. You will get all P tags in an array, even if it's just one. Commented Oct 3, 2020 at 8:03

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

I was just editing my answer.You had done before that.Thank you so much.
This is also giving NaN value for valueCount. The HTML file cannot be edited it will be same <p>-</p> . It should be done without changing HTML. This answer is the same as was mine.
0

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;

2 Comments

document.querySelector("#ones p") is much shorter.
yeah, also in getElementsByTagName('p').textContent textContent is undefined, because getElementsByTagName('p') returns array, so yeah, querySelector is better in this case, you'll get first element from array of elements matched to selector

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.