。我如何parentNode.removeChild();一个div。用数组中的名字? (普通Java脚本)

时间:2017-04-12 19:53:36

标签: javascript html dom

我知道标题听起来很奇怪,但我不知道如何准确描述我的问题。我有一个数组,其中包含我之前创建的所有div id。现在我想获取第一个div的id并通过parentNode.removeChild()删除div;控制台打印: '无法检索未定义或空引用的“removeChild”属性。'

我希望你能帮助我:)

var animation_time = 1500;
var div_id_selection = [];//it contains 'div0', div1, div2 ... divn
var array_counter = -1;

// Before that is a function that creates a div by document.createElement("div); with the id div0, div1, div2 ...than it writes the id into the array:
  div_id_selection.push('div' + id);

var delete_divs = function(){

                  setTimeout(function(){
                  array_counter += 1;
                  var div_to_delete = div_id_selection[array_counter];
                  //var div_to_delete_str = div_to_delete.toString(); I already tried it with the string-didn´t work
                  console.log(div_to_delete);
                  console.log(array_counter);
                  div_to_delete.parentNode.removeChild(div_to_delete); // here is the problem
                  }, animation_time);
                }

1 个答案:

答案 0 :(得分:1)

div_to_delete是一个字符串(id,存储在数组中)。

parentNode方法仅适用于DOM对象。

您必须先使用id选择元素。

// get the correct DOM object using the array
var elem = document.getElementById(div_to_delete);
elem.parentNode.removeChild(elem);