2017-04-12 17 views
1

我知道標題聽起來很奇怪,但我不知道如何正確描述我的問題。我有一個數組與我以前創建的所有divs id。現在我想取第一個div的id並通過parentNode.removeChild()移除div;控制檯打印: '未定義或空引用的「removeChild」屬性無法檢索。'。我如何parentNode.removeChild();一個div。在數組中的名稱? (普通的Java腳本)

我希望你能幫助我與:)

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

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); 
+0

嘿謝謝它現在正在工作:) –

+0

@Helmet_Gaming很高興爲它工作:) –

相關問題