【问题标题】:Replacing a label's text if there's a nested input element如果有嵌套的输入元素,则替换标签的文本
【发布时间】:2016-11-08 19:41:38
【问题描述】:

更改标签的文本似乎easy

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

或者,使用 jQuery

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

如果标签包含<input/> 元素,则上述两种方法都不能正常工作:

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

-- 在这种情况下,&lt;input/&gt; 元素与旧文本一起被替换。

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

【问题讨论】:

    标签: javascript jquery html label


    【解决方案1】:

    过滤掉非空文本子节点,替换成新的内容。

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

    【讨论】:

    • 非常酷。如需更多参考,请参阅nodeType
    【解决方案2】:

    使用 javascript nextSibling 属性选择输入的同级文本。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      相关资源
      最近更新 更多