5

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?

Bass
  • 4,977
  • 2
  • 36
  • 82

2 Answers2

9

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>
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • 2
    Very cool. For more reference, see [nodeType](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType). – showdev Jul 06 '16 at 16:59
1

Use javascript nextSibling property to selecting sibling text of input.

document.querySelector('input').nextSibling.nodeValue = "newText";
<label>
    <input type="checkbox">
    Text
</label>
Mohammad
  • 21,175
  • 15
  • 55
  • 84