浏览器已经拥有一个完美的解析HTML树形结构在o.node
中。将文档内容序列化为HTML(使用innerHTML
),试图用正则表达式修改它(无法可靠地解析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;
};