0
<div class="here_is_div">
    <label class="a_label">
            <input type="checkbox" name="checkbox">
            Hello world
    </label>
</div>

I thought textContent would be able to just change the TEXT

document.getElementsByTagName('label')[0].textContent = "Hello World is replaced"

However, textContent replaces everything including checkbox. Is there a better way to just change text without doing something like below:

document.getElementsByTagName('label')[0].innerHTML = '<input type="checkbox" name="checkbox">Hello world is replaced';
1
  • Get the textNode child of the label and change it. Commented May 24, 2018 at 3:57

2 Answers 2

3

You'll need to select the text node specifically.

document.querySelector('label').childNodes[2].textContent = 'Hello World is replaced';
<div class="here_is_div">
    <label class="a_label">
            <input type="checkbox" name="checkbox">
            Hello world
    </label>
</div>

Note that you have 3 child nodes of the label here: the whitespace and newline between the label and the input, the input itself, and the Hello world and surrounding whitespace.

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

Comments

0

You can wrap the text inside a span tag:

document.querySelector('label span').textContent = 'Hello World is replaced';
<div class="here_is_div">
    <label class="a_label">
            <input type="checkbox" name="checkbox">
            <span>Hello world</span>
    </label>
</div>

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.