javascript - JS Looped appendChild producing strange behaviour -
i have function:
//add links called classes function addlinks () { var classelements = []; var idelements = []; var finalrender; var expand = document.createtextnode("+"); var contract = document.createtextnode("-"); var elementslist = []; var count = 0; //create dom nodes renderpelements = document.createelement ("p"); renderaelements = document.createelement ("a"); renderaelements.setattribute("href", "#"); renderaelements.setattribute("class", "expander"); renderaelements.appendchild(expand); finalrender = renderpelements.appendchild(renderaelements); //get arrays of elements class or id set provided string (var = 0; i< show_hide_class_selectors.length; i++) { classelements[i] = document.getelementsbyclassname(show_hide_class_selectors[i]); //if prevents null value appearing in array , freezing script if (document.getelementbyid(show_hide_class_selectors[i])) { idelements[i] = document.getelementbyid (show_hide_class_selectors[i]); } } //loop though selected id's / classes , generate single array of selected elements (var = 0; i< idelements.length; i++) { elementslist[count] = idelements[i]; count = count +1; } //must loop twice variable 2 dimensional i=class name y=elements of class (var = 0; i< classelements.length; i++) { (var y = 0; y< classelements[i].length; y++) { elementslist[count] = classelements[i][y]; count = count +1; } } //render (var = 0; i< elementslist.length; i++) { alert ("render"); elementslist[i].parentnode.firstchild.appendchild(finalrender); alert (elementslist[i]); } }
which meant take array of classes / ids provided global variables , produce array contains requested elements. supposed append childnodes (links in case) sibling nodes looping though generated array using appendchild.
however instead of resulting in page has bunch of links on it, final loop instead appends child , removes it, working way though loop until final element permitted retain it's generated link.
i can find no explaination behaviour or similiar problem.
you can't append element more 1 spot in dom. need append separate copy of finalrender
(and descendants) each time through loop:
elementslist[i].parentnode.firstchild.appendchild(finalrender.clonenode(true));
keep in mind different browsers handle cloning elements bound events differently: end clone having same events bound original, others not.
also, loops screaming brevity. middle 2 can replaced just:
elementlist = idelements; (var i=0; i<classelements.length; ++i) elementlist = elementlist.concat(classelements[i]);
or, better, construct elementlist
directly within first loop, don't make bunch of arrays don't use later, or best, append right in first loop.
Comments
Post a Comment