All this (and the stuff above) should be done as string outside of the DOM then insert the complete HTML into the DOM. Much more costly to insert into the DOM then manipulate.