浏览器已经有一个完美解析的 HTML 树o.node
。将文档内容序列化为 HTML(使用innerHTML
),尝试用正则表达式破解它(cannot可靠地解析 HTML),然后通过设置将结果重新解析回文档内容innerHTML
……实在是有点逆天了。
相反,检查内部已有的元素和属性节点o.node
,删除那些你不想要的,例如:
filterNodes(o.node, {p: [], br: [], a: ['href']});
定义为:
// Remove elements and attributes that do not meet a whitelist lookup of lowercase element
// name to list of lowercase attribute names.
//
function filterNodes(element, allow) {
// Recurse into child elements
//
Array.fromList(element.childNodes).forEach(function(child) {
if (child.nodeType===1) {
filterNodes(child, allow);
var tag= child.tagName.toLowerCase();
if (tag in allow) {
// Remove unwanted attributes
//
Array.fromList(child.attributes).forEach(function(attr) {
if (allow[tag].indexOf(attr.name.toLowerCase())===-1)
child.removeAttributeNode(attr);
});
} else {
// Replace unwanted elements with their contents
//
while (child.firstChild)
element.insertBefore(child.firstChild, child);
element.removeChild(child);
}
}
});
}
// ECMAScript Fifth Edition (and JavaScript 1.6) array methods used by `filterNodes`.
// Because not all browsers have these natively yet, bodge in support if missing.
//
if (!('indexOf' in Array.prototype)) {
Array.prototype.indexOf= function(find, ix /*opt*/) {
for (var i= ix || 0, n= this.length; i<n; i++)
if (i in this && this[i]===find)
return i;
return -1;
};
}
if (!('forEach' in Array.prototype)) {
Array.prototype.forEach= function(action, that /*opt*/) {
for (var i= 0, n= this.length; i<n; i++)
if (i in this)
action.call(that, this[i], i, this);
};
}
// Utility function used by filterNodes. This is really just `Array.prototype.slice()`
// except that the ECMAScript standard doesn't guarantee we're allowed to call that on
// a host object like a DOM NodeList, boo.
//
Array.fromList= function(list) {
var array= new Array(list.length);
for (var i= 0, n= list.length; i<n; i++)
array[i]= list[i];
return array;
};