事先声明,去除空白文本节点的函数是剽窃的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>removeWhite1</title>
</head>
<style>
span {
background-color: purple;
color: white;
}
</style>
<body>
<p>
<span>1</span>
<span>2</span>
<span>3</span>
<span>4</span>
<span>5</span>
<span>6</span>
<span>7</span>
<span>8</span>
<span>9</span>
<span>10</span>
</p>
<script>
function removeWhiteSpace(elem){
let el = elem || document,
cur = el.firstChild,
temp,
reg = /\S/;
while(null != cur){
temp = cur.nextSibling;
if( 3 === cur.nodeType && !reg.test(cur.nodeValue) ){
el.removeChild(cur);
}else if( 1 === cur.nodeType ){
removeWhiteSpace(cur);
}
cur = temp;
}
}
removeWhiteSpace();
</script>
</body>
</html>
文章最初发布在简书,时间为 2018.07.23 19:51 。