Cloning a fieldset and changing IDs with plain JavaScript?
I know how to clone objects using plain JavaScript and increment the number, however I was wondering what the best approach is to replacing IDs and other attribu开发者_如何转开发tes like "for" for label elements so they are not duplicated when the cloned fieldsets are appended to the form.
Can someone give me a quick example of how to do this using plain ole' JavaScript?
Clone the nodes as normal, and mutate them before inserting them into the document. It doesn't matter if two Element nodes exist with the same ID, as long as they aren't both inserted into the document's childNodes tree at the same time.
var copy= document.cloneNode(element);
n++;
copy.getElementsByTagName('label')[0].htmlFor= 'thing'+n;
copy.getElementsByTagName('input')[0].id= 'thing'+n;
element.parentNode.appendChild(copy);
You can write your "label" without "for" like this :
<p><label>Text 1 : <input type="text" name="text[]" /></label></p>
<p><label>Text 2 : <input type="text" name="text[]" /></label></p>
<p><label>Text 3 : <input type="text" name="text[]" /></label></p>
精彩评论