Reputation: 5271
<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';
Upvotes: 0
Views: 201
Reputation: 58
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>
Upvotes: 0
Reputation: 371049
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.
Upvotes: 3