Possible Duplicate:
What is better, appending new elements via DOM functions, or appending strings with HTML tags?
I need to change one thousand <div>‘s — just two attributes. Would it be “cheaper” to remove/add the whole <div>, or just change the attributes? And what would be the cheapest way to do this with Javascript (without leaks, and with as little GC as possible).
Test it in your target browsers, but given that changing attributes wouldn’t usually require a reflow (obviously depending on what the attributes are, how they affect how styles are applied, etc., etc.) and doesn’t require changing links between DOM nodes, I’d tend to expect changing the attributes to be faster. Replacing the content will require tearing down the old DOM nodes, creating new ones, hooking them into the DOM…
As for how to do it, it depends a bit on how you identify the divs, but it’s going to be a simple loop regardless. For example, on any modern browser:
If the attributes are reflected as properties, you may want to use the reflected property instead to avoid the
setAttributefunction call. For instance,div.id = "value";rather thandiv.setAttribute("id", "value");. But I bet that’s premature optimization.