Bass Bass - 4 months ago 9
jQuery Question

Replacing a label's text if there's a nested input element

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?

Answer

Filter out the non-empty text child nodes and replace it with the new content.

$('label').contents().filter(function() {
  return this.nodeType === 3 && this.textContent.trim().length;
}).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');

label.childNodes[2].textContent = 'new text'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox">Text</label>

Comments