Home >Web Front-end >JS Tutorial >Proficient in JavaScript, correct the cleanWhitespace function_javascript class library

Proficient in JavaScript, correct the cleanWhitespace function_javascript class library

WBOY
WBOYOriginal
2016-05-16 18:32:451272browse
Copy code The code is as follows:

function cleanWhitespace(element){
//If no parameters are provided , then process the entire HTML document
element = element || document;
//Use the first child node as the start pointer
var cur = element.firstChild;
//Temporary variables are used to save The next node of the current node
var tmp;
//Until there are no child nodes
while (cur != null){
//Save the next node of the current node
tmp =cur.nextSibling
//If the node is a text node, it should contain spaces
if ( cur.nodeType == 3 && ! /S/.test(cur.nodeValue)){
//Delete This text node
element.removeChild( cur );
//Otherwise, it is an element
} else if (cur.nodeType == 1){
//Recurse the entire document
cleanWhitespace( cur );
}
cur = tmp;//Traverse child nodes
}
}

Also transfer a usable
Copy code The code is as follows:

function cleanWhitespace2(node) {
var notWhitespace = /S/;
for (var i=0; i < node.childNodes.length; i ) {
var childNode = node.childNodes[i];
if ((childNode.nodeType == 3)&&(!notWhitespace .test(childNode.nodeValue))) {
node.removeChild(node.childNodes[i]);
i--;
}
if (childNode.nodeType == 1) {
cleanWhitespace2(childNode);
}
}
}

If you only clear the white space of this node, the child nodes will not be traversed
Copy code The code is as follows:

function cleanWhitespace2(oEelement)
{
for(var i=0;ivar node=oEelement.childNodes[i];
if(node.nodeType==3 && !/S/.test(node.nodeValue)){node.parentNode. removeChild(node)}
}
}

Also transfer a usable one
Copy code The code is as follows:

function cleanWhitespace2(node) {
var notWhitespace = /S/;
for (var i=0; i < node.childNodes.length ; i ) {
var childNode = node.childNodes[i];
if ((childNode.nodeType == 3)&&(!notWhitespace.test(childNode.nodeValue))) {
node.removeChild (node.childNodes[i]);
i--;
}
if (childNode.nodeType == 1) {
cleanWhitespace2(childNode);
}
}
}

If you only clear the blank of this node, do not traverse the child nodes
Copy code The code is as follows:

function cleanWhitespace2(oEelement)
{
for(var i=0;ivar node=oEelement. childNodes[i];
if(node.nodeType==3 && !/S/.test(node.nodeValue)){node.parentNode.removeChild(node)}
}
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn