Replacing shortcut text if there is a nested input element

Changing the label text seems simple :

var /**HTMLLabelElement*/ label = ...; label.innerHTML = "..."; 

or using jQuery:

 var /**HTMLLabelElement*/ label = ...; $(label).text("..."); 

None of the above actions work correctly if the label wraps the <input/> element:

 <label><input type="checkbox">Text</label> 

- in this case, the <input/> element is replaced with the old text.

How to change only label text without affecting its children?

+5
source share
2 answers

Filter out non-empty text child nodes and replace them with 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> 
+8
source

Use the javascript nextSibling property to select the text to enter text.

 document.querySelector('input').nextSibling.nodeValue = "newText"; 
 <label> <input type="checkbox"> Text </label> 
+1
source

All Articles