I have this HTML structure:
<p id="lorem">
<span class="part" id="n01">L</span><span class="part" id="n02">o</span><span class="part" id="n03">r</span><span class="part" id="n04">e</span><span class="part" id="n05">m</span> <span class="part" id="n06">i</span><span class="part" id="n07">p</span><span class="part" id="n08">s</span><span class="part" id="n09">u</span><span class="part" id="n10">m</span>
</p>
<h1>Click Me</h1>
and this JavaScript code:
arrRed = ["#n01", "#n04", "#n05", "#n09"];
arrBlue = ["#n02", "#n07", "#n08"];
$("h1").click(function(){
$.each(arrRed, function( i, v ){
$(v).addClass("red");
});
$.each(arrBlue, function( i, v ){
$(v).addClass("blue");
});
})
When the h1 is clicked, certain letters get a certain color. The problem with that is the performance, I trigger too much reflows/repaints.
In another question someone told me to use parent.cloneNode(true) and parent.parentNode.replaceChild(clone, parent). So I clone the elements, change them and but them back in place, triggering only one reflow.
So I cloned the parent element:
var doc = document;
var lorem = doc.getElementById("lorem");
var clone = lorem.cloneNode(true)
But how do I have to proceed now? I somehow have to modify the elements in clone and then replace them, but using $.each again to edit them does not seem to be a good idea.
Try this:
Fiddle
Create a
clone, filter the children of this new cloned element twice to apply the classes and finally replace the old element entirely with the new one.Or, if you prefer, using
findinstead offilterwhile iterating over the arrays:Fiddle