开发者问题收集

Javascript - 未捕获的类型错误:无法读取未定义的属性“removeChild”

2019-10-15
2251

我有以下标记:

<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>

以及以下用于删除按钮的 javascript:

window.onload = function (){

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

但我收到以下错误:

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

console.log 返回:

NodeList [button.button.button-chevron-right.button-primary]  
2个回答

由于您正在按类名查询元素,因此您将收到一个数组。

只需更改此行: 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
2019-10-15

getElementsByName() 返回文档中具有给定名称的元素的 NodeList 集合 ,要从中访问任何元素,您应该使用特定的 索引

您可以尝试使用 querySelector() ,它 返回文档中与指定选择器或选择器组 和属性选择器匹配的第一个元素:

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
2019-10-15