简体   繁体   English

如果存在嵌套的输入元素,则替换标签的文本

[英]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 : 或者,使用jQuery

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

Neither of the above works correctly if the label wraps the <input/> element: 如果标签包装<input/>元素,则上述任何一种都无法正常工作:

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

-- in this case, the <input/> element is replaced along with the old text. - 在这种情况下, <input/>元素将与旧文本一起替换。

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 纯JavaScript方法

 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> 

Use javascript nextSibling property to selecting sibling text of input. 使用javascript nextSibling属性选择输入的兄弟文本。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM