Trim 白色 space 来自标签而不移除内部 <input>

Trim white space from label without removing inside <input>

我的html:

<div class="product-addon product-addon-extra-tip">
    <p class="form-row form-row-wide addon-wrap-2004-extra-tip-0-0">
        <label><input type="radio" class="addon-radio" name="addon-2004-extra-tip-0[]" value="2"> 2 </label>
    </p>
    <p class="form-row form-row-wide addon-wrap-2004-extra-donation-to-trafficking-survivors-0-1">
        <label><input type="radio" class="addon-radio" name="addon-2004-extra-tip-0[]" value="5"> 5 </label>
    </p>
</div>

您可以看到标签的数字两边都有空格。我的 javascript 只用于 trim 那个空格,但它也消除了整个 input 标签。

var labels = document.querySelectorAll("div.product-addon label");
for (var i = 0; i < labels.length; i++) {
  labels[i].textContent = labels[i].textContent.trim();
}

innerTextinnerHTML 无法代替 textContent。我做错了什么?

textContentinnerTextinnerHTML,它们都将内容替换为您分配的任何值,因此输入被删除。

您应该做的是遍历子节点,仅过滤掉文本节点,并仅修剪这些节点的内容。

var labels = document.querySelectorAll("div.product-addon label");
for (var i = 0; i < labels.length; i++) {
    var children = labels[i].childNodes;
 
    for (var j = 0; j < children.length; j++) {
     if ( children[j].nodeType === 3 ) 
         children[j].nodeValue = children[j].nodeValue.trim();
    }
}
<div class="product-addon product-addon-extra-tip">
    <p class="form-row form-row-wide addon-wrap-2004-extra-tip-0-0">
        <label><input type="radio" class="addon-radio" name="addon-2004-extra-tip-0[]" value="2"> 2 </label>
    </p>
    <p class="form-row form-row-wide addon-wrap-2004-extra-donation-to-trafficking-survivors-0-1">
        <label><input type="radio" class="addon-radio" name="addon-2004-extra-tip-0[]" value="5"> 5 </label>
    </p>
</div>