Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 264
Bass Avatar asked Jul 06 '16 16:07

Bass


1 Answers

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>
like image 151
Pranav C Balan Avatar answered Nov 07 '22 12:11

Pranav C Balan