codenoob codenoob - 3 months ago 30
Javascript Question

Jquery append then update element id

https://jsfiddle.net/codenoob/cavrnyv0/6/

please see jsfiddle.

I have a button that append a new row to the table. then I want to update the id for the newly added row so each row is unique. however the squence is wrong.

for example. I expect getting

original
newrow 1
newrow 2
newrow 3


instead I get

newrow 1
newrow 2
newrow 3
original


if you check element on developer tool. you will notice. It is not appending before original, but it is renaming the original to be newrow1.

what did I do wrong.

Answer

You don't need to use html() for cloning - jquery comes with a clone feature that is much more efficient.

Also, you always want to make as many changes to a DOM node as you can before inserting it into the DOM. In this case, you want to set the ID of the new select box before you attach the new row. The reason is because once a DOM node has been inserted (eg, you can see it in the page), every change causes it to be rerendered - which is just inefficient.

Take a look at this updated fiddle:

https://jsfiddle.net/cavrnyv0/8/