从标签修剪空白区域而不删除<input />内部

时间:2016-02-24 02:24:57

标签: javascript innerhtml innertext

我的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只是为了修剪那个空格,但它也消除了整个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。我做错了什么?

1 个答案:

答案 0 :(得分:2)

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

你应该做的是迭代子节点,过滤掉只有文本节点,然后修剪那些内容。

&#13;
&#13;
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();
    }
}
&#13;
<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>
&#13;
&#13;
&#13;