如何清理DOM节点

时间:2015-11-22 19:38:24

标签: javascript dom

我需要删除不必要的空格和HTML节点的头部。

例如,对于此节点p

<p>
   The cat 
   <b>
       <span>is on </span>
       <em><span>the bed</span></em>
   </b>
</p>

我想获得:

<p>The cat <b><span>is on </span><em><span>the bed</span></em></b></p>

因此,如果node包含根p的DOM树,并执行以下代码:

var text = node.innerText;
console.log(text);

我得到The cat而不是 The cat

我找到了这个方法:

function clean(node)
{
  for(var n = 0; n < node.childNodes.length; n ++)
  {
    var child = node.childNodes[n];
    if
    (
      child.nodeType === 8 
      || 
      (child.nodeType === 3 && !/\S/.test(child.nodeValue))
    )
    {
      node.removeChild(child);
      n --;
    }
    else if(child.nodeType === 1)
    {
      clean(child);
    }
  }
}

我尝试过:

clean(node);
var text = node.innerText;
console.log(text);

我总是获得 The cat

为什么呢?我怎样才能解决我的问题?

由于

如果我有:

 <p>cat_</p>

 <p>
     cat_
 </p>

我想永远获得cat_而不是 cat_

2 个答案:

答案 0 :(得分:1)

您可以使用 String.prototype.trim()方法,它会删除前导空格

var spaces = "       your text     "
var required = spaces.trim()

现在required = "your text"

答案 1 :(得分:1)

这将对您有所帮助:

function whitespaceSimplify(str: string): string {
    str = str.replace(/\s+/g, " ") // Replace all whitespace in a row with a simple space sign
    return str
}

你可以在HTML-Code上使用它删除任何疑惑的空格:

clean(node);
node.innerHTML = whitespaceSimplify(node.innerHTML)

或在干净的

中使用whitespaceSimplify(string)

演示:

function clean(node) {
  for (var n = 0; n < node.childNodes.length; n++) {
    var child = node.childNodes[n];
    if (
      child.nodeType === 8 ||
      (child.nodeType === 3 && !/\S/.test(child.nodeValue))
    ) {
      node.removeChild(child);
      n--;
    } else if (child.nodeType === 1) {
      clean(child);
    }
  }
}

function whitespaceSimplify(str) {
  str = str.replace(/\s+/g, " ") // Replace all whitespace in a row with a simple space sign
  return str
}


var node = document.getElementById('node')
clean(node)
node.innerHTML = whitespaceSimplify(node.innerHTML)

document.getElementById('output').innerText = node.innerHTML
<div id="node">
  <p>
    The cat 
    <b>
      <span>
        is on 
      </span>
      <em><span>the bed</span></em>
    </b>
  </p>
</div>
<code id="output"></code>

返回:    <p> The cat <b><span> is on </span><em><span>the bed</span></em></b></p>