Changing the text of a label seems easy:
var /**HTMLLabelElement*/ label = ...;
label.innerHTML = "...";
or, using jQuery:
var /**HTMLLabelElement*/ label = ...;
$(label).text("...");
Neither of the above works correctly if the label wraps the <input/>
element:
<label><input type="checkbox">Text</label>
-- in this case, the <input/>
element is replaced along with the old text.
How do I change just the text of a label, without affecting its child elements?
Filter out the non-empty text child nodes and replace it with the new content.
$('label')
// get all child nodes including text and comment
.contents()
// iterate and filter out elements
.filter(function() {
// check node is text and non-empty
return this.nodeType === 3 && this.textContent.trim().length;
// replace it with new text
}).replaceWith('new text');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="checkbox">Text</label>
Pure JavaScript method
var label = document.querySelector('label');
// get all child nodes and update the text node from it
label.childNodes[2].textContent = 'new text'
// If you don't know the position
// then iterate over them and update
// based on the node type
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="checkbox">Text</label>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With