1

So basically I want to change the text in a div using javascript. I managed to do it, but I encountered a problem: the tag in which that text was doesn't work anymore for the javascript changed text.

I tried changing .textContent to .innerHTML

<div class="nr11"><h1>11</h1></div>

let lastPosition=document.querySelector('.nr'+player.lastPosition);
lastPosition.textContent=player.lastPosition;

I expect for the text ( number 11 in my case ) to be changed with player.lastPosition while still having active for player.lastPosition.

3 Answers 3

2

Just change the selector to select the h1 element instead of the div:

let player = {lastPosition: 11};
let lastPosition = document.querySelector('.nr' + player.lastPosition + '>h1');
// or with a template string: `.nr${player.lastPosition}>h1`
lastPosition.textContent = player.lastPosition;
<div class="nr11"><h1>11</h1></div>

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

Comments

1

You are overwriting the entire <h1>11</h1> content.

What you want to actually do is to change the 11 inside the <h1>, so you need to select that element, instead of selecting the <div> that contains the <h1>:

var player = {
    lastPosition: 11
};
let lastPosition=document.querySelector('.nr'+player.lastPosition+'>h1');
lastPosition.textContent=player.lastPosition;
<div class="nr11"><h1></h1></div>

Comments

1

problem here is you are changing the <div> element text, which is: <h1>11</h1> to your new text.

This means you are replacing the whole thing instead of just the value 11. To solve this issue you can simply change where you are querying for the element to:

let lastPosition = document.querySelector('.nr' + player.lastPosition + ' h1');
lastPosition.textContent = player.lastPosition;

This way the variable lastPosition will be the h1 element, therefore you will be changing the h1 textContent.

Comments

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.