Created
July 17, 2014 05:49
-
-
Save hehongwei44/9105deee7b9bde88463b to your computer and use it in GitHub Desktop.
清楚节点内的空格
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function cleanWhitespace(element) { | |
//如果不提供参数,则处理整个HTML文档 | |
element = element || document; | |
//使用第一个节点作为开始指针 | |
var cur = element.firstChild; | |
//一直循环,直到没有子节点为止。 | |
while (cur != null) { | |
//如果节点是文本节点,并且只包含空格 | |
if ((cur.nodeType == 3) && !/\S/.test(cur.nodeValue)) { | |
element.removeChild(cur); | |
} | |
//一个节点元素 | |
else if (cur.nodeType == 1) { | |
//递归整个文档 | |
cleanWhitespace(cur); | |
} | |
cur = cur.nextSibling; //遍历子节点 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment