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

时间:2016-07-06 16:46:05

标签: javascript jquery html label

更改标签文字似乎easy

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

或使用 jQuery

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

如果标签包裹<input/>元素,则上述任何一种都无法正常工作:

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

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

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

2 个答案:

答案 0 :(得分:8)

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

&#13;
&#13;
$('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');
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox">Text</label>
&#13;
&#13;
&#13;

纯JavaScript方法

&#13;
&#13;
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
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
  <input type="checkbox">Text</label>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用javascript nextSibling属性选择输入的兄弟文本。

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