This process does not work in JavaScript: createElement() -> setAttribute('id') -> getElementById()
Posted
by
kristovaher
on Stack Overflow
See other posts from Stack Overflow
or by kristovaher
Published on 2012-04-08T17:25:56Z
Indexed on
2012/04/08
17:29 UTC
Read the original article
Hit count: 174
I was so sure that this question has been answered a thousand times before, but I've been unable to find an answer in StackOverflow. If there is already an answer and I was unable to find it then I apologize.
I create hidden form elements dynamically like this:
submitForm=document.getElementById('my-form');
var element=document.createElement('input');
element.id='hidden-form-data'; // or setAttribute('id','hidden-form-data');
element.name='my-hidden-form-data';
element.type='hidden';
element.value='my-data';
submitForm.appendChild(element);
This works and the input field is created and it is taken into account when submitting the form.
But I want to remove it after I have dynamically created it. I was sure that creating a new node this way would be 'correct' for browser and DOM, but apparently it is not.
This returns null:
element=document.getElementById('hidden-form-data');
if(element!=null){
element.parentNode.removeChild(element);
}
But it never gets removed and is always null.
Is there any way I can remove a dynamically created node with an ID?
Thank you!
Please do not suggest jQuery, it's not possible to use jQuery for this, footprint is too heavy for such a small task
I could not get a working answer from here, which was the closest thread I could find.
© Stack Overflow or respective owner