Remove Form Elements or any Element from Web Page (DOM) using JavaScript

Today I need to remove a form element from page based on certain input from customer. I used to do document.getElementById('myID').style.display = 'none'; and it was enough all the time. User cannot see and cannot use that element. But today it has not worked. What was the reason for that? The above code used to hide the element from display but not from the DOM list.

My situation:

I have an optional Input box for promo code, which can be filled by user who have promocode. Based on the promo code, I may have to hide one option from the two options. Options could be more.

So, based on my earlier way of working with this, I used to hide an option based on input. Now, out of two option, only one option left after hiding another one, it should be selected. I could select another visible option based on user input easily, but it would have worked when there can only be two options. In case of more options left after disabling one option, I could not decide one option on behalf of user. So, I thought to select the top one. In this case, if only one option will be there after disabling one then users will not have any choice and that should be selected by choice. In case of more than one options left, I should not have selected any one but still I decided to select top one.

Now, the story is over and you know that my usual method was not working, I thought of it and come to understand that I need to completely remove that element. In case of above situation, If I have disabled first one and tried to select the top one then it got the disabled one, because in iteration over the options that element came into consideration. So, the need to remove the element from the DOM itself.

To remove the element from the DOM:

Method 1: You know the parent element

  • Get element reference
  • Get element's parent reference
  • parentRef.removeChild('element');
<script type="text/javascript">
d = document;
var ele = d.getElementById('elementID');
var parentEle = d.getElementById('parentElementID');

Method 2: You do not know the parent element in advance

  • Get element reference
  • element.parentNode.removeChild(element);
<script type="text/javascript">
var ele = document.getElementById('elementID');
Comments are open for an year period. Please, write here on Facebook page.