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

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

更改标签的文本似乎 easy:

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

或者,使用 jQuery:

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

如果标签包含 <input/> 元素,则以上都不能正常工作:

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

-- 在这种情况下,<input/> 元素与旧文本一起被替换。

如何只更改标签的文本而不影响其子元素?

过滤掉非空文本子节点并替换为新内容

$('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>


纯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>

使用javascriptnextSibling属性来选择输入的同级文本。

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