这是一个可能的解决方案,使用document.createTreeWalker从选定元素及其所有子元素中删除属性。
HTML
<div id="removeHere" title="titled 0">
<div title="titled 1">some text 1</div>
<div title="titled 2">some text 2
<div title="titled 3">some text 3
<div title="titled 4">some text 4</div>
</div>
</div>
<div title="titled 5">some text 5</div>
</div>
<div title="titled 6">some text 6</div>
Javascript
(function (global) {
function removeAttributeWalker(node, attribute) {
var treeWalker = document.createTreeWalker(
node,
NodeFilter.SHOW_ELEMENT, {
acceptNode: function () {
return NodeFilter.FILTER_ACCEPT;
}
},
false);
node.removeAttribute(attribute);
while (treeWalker.nextNode()) {
treeWalker.currentNode.removeAttribute(attribute);
}
}
global.addEventListener("load", function onLoad() {
global.removeEventListener("load", onLoad);
removeAttributeWalker(document.getElementById("removeHere"), "title");
}, false);
}(window));
在jsfiddle 上
更新:如果您需要支持没有上述方法的旧浏览器,则可以使用以下方法。
Javascript
(function (global) {
function removeAttributeWalker(node, attribute) {
if (node.nodeType === 1) {
node.removeAttribute(attribute);
node = node.firstChild;
while (node) {
removeAttributeWalker(node, attribute);
node = node.nextSibling;
}
}
}
global.addEventListener("load", function onLoad() {
global.removeEventListener("load", onLoad);
removeAttributeWalker(document.getElementById("removeHere"), "title");
}, false);
}(window));
在jsfiddle 上