Disable attribute of element in the DOM
I'm using cloneNode(true)
to make copies of DOM elements (for instance a div containing some spans which contain text and may be nested). I want to remove all of the id attributes from the copies, so that document.getElementById
will find the original item.
How do I do this? node.setAttribute('id','');
seems to work, but I'm wondering if this is removing it, or simply setting its id to a zero length string (which still means I have a multitude of elements which have the same id).
Also I'm wondering about how I might recursively go about erasing id's so I can ensure that all id's in copies are wiped, so I can safely continue referencing items (the originals of course) by id. So far I have this:
function recursive_erase_id(node) {
node.setAttribute('id','');
var children = node.childNodes;
if (children) recursive_erase(children);
}
开发者_JAVA技巧
As for the recursion, this should work (untested, though):
function recursive_erase_id(node) {
if (node.removeAttribute) { // Or node.nodeType == Node.ELEMENT_NODE
// Or even node.nodeType == 1 (IE and Opera does not define the NodeType constants!)
node.removeAttribute('id');
}
var children = node.childNodes;
for (var i = 0, j = children.length; i < j; i++) {
recursive_erase_id(children.item(i)); // Depth-first.
}
}
How about node.removeAttribute('id')
?
I have constructed a fiddle here. It uses removeAttribute
and a recursive function to remove the id's from the original. An alternative is setting the id to null. Both work. If you fiddle around with the fiddle ;-) and inspect the cloned elements with the dom inspector from you browser, you'll see all the clones don't have an id anymore.
To answer your first question, you will need to use removeAttribute(name) instead of setting the attribute to an empty string. You can set the new attribute upon copying via setAttribute, but I'd recommend doing it after you remove the old one.
Your second question involves the removal of attributes upon copying. Perhaps creating a custom function like so would solve the issue when copying:
var customClone = function(el) {
var newElement = el.cloneNode(true);
newElement.removeAttribute('id'); // set later on?
}
Hope that provides some guidance.
Also be noted that the cloneNode()
method doesn’t copy JavaScript properties that you add to DOM
nodes, such as event handlers. This method copies only attributes and, optionally,
child nodes. Everything else is lost. IE has a bug where event handlers are also
cloned, so removing event handlers before cloning is recommended.
精彩评论