0

I have the following markup:

<div>
  <div class="form-action form-action-primary">
   <button class="button button-chevron-right button-primary" name="next" type="submit" value="Next">
            Next
          <span class="icon icon-icon-cta"></span>
   </button>
  </div>
</div>

and the following javascript to remove the button:

window.onload = function (){

    var elem = document.getElementsByName('next');
    console.log(elem);
    elem.parentNode.removeChild(elem);
}; 

but I get the following error:

Uncaught TypeError: Cannot read property 'removeChild' of undefined
at window.onload 

console.log returns:

NodeList [button.button.button-chevron-right.button-primary]  
adam78
  • 9,668
  • 24
  • 96
  • 207
  • 1
    For starters I think you can't call `removeChild` on a `NodeList`, which is what `getElementsByName` returns. Please add the output of `console.log(elem)` to the question. – Ayrton Oct 15 '19 at 11:33
  • Possible duplicate of [child.parentNode.removeChild(child) keeps giving a TypeError: Cannot read property 'removeChild' of undefined](https://stackoverflow.com/questions/32152377/child-parentnode-removechildchild-keeps-giving-a-typeerror-cannot-read-proper) – Sumit Ridhal Oct 15 '19 at 11:37
  • Possible duplicate of [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Sebastian Simon Oct 15 '19 at 11:40

2 Answers2

2

Since you are querying for elements by class name, you will receive an array.

Just change this line: var elem = document.getElementsByName('next');

window.onload = function() {
  var elem = document.getElementsByName('next')[0]; // Element at index 0
  console.log(elem);
  elem.parentNode.removeChild(elem);
};
<div>
  <div class="form-action form-action-primary">
    <button class="button button-chevron-right button-primary" name="next" type="submit" value="Next">
            Next
          <span class="icon icon-icon-cta"></span>
   </button>
  </div>
</div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

getElementsByName() returns a NodeList Collection of elements with a given name in the document, to access any element from it you should use the specific index:

You can try with querySelector() which returns the first Element within the document that matches the specified selector, or group of selectors and attribute selector:

window.onload = function (){
    var elem = document.querySelector('[name=next]');
    console.log(elem);
    elem.parentNode.removeChild(elem);
};
<div>
  <div class="form-action form-action-primary">
   <button class="button button-chevron-right button-primary" name="next" type="submit" value="Next">
      Next
      <span class="icon icon-icon-cta"></span>
   </button>
  </div>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59