无法将节点附加到空div

时间:2017-10-27 03:42:41

标签: javascript html dom

<div id = "first"></div>
<div id = "second"></div>
<div id = "third"></div>

尝试在javascript函数中动态附加到这些div

if (condition??) variable = "first"
else if (condition) variable = "second"
else variable = "third"

let div = document.getElementById(variable);

根据某些条件,上面的变量可以是第一,第二或第三。

div.appendChild(img)  
div.appendChild(text)

然而,由于div最终为null,因此无法向其添加任何内容,因为以下错误。

Cannot read property 'appendChild' of null.

所以任何想法如何解决这个问题?

编辑:添加了实际的代码片段

// my html
<div id = "list" class = "center"> Listing <br><br>
    <div id = "first"></div>
    <div id = "second"></div>
    <div id = "third"></div>
</div>

//my js
$.ajax({
        async: true,
        type: 'GET',                
        url: "rankings/" + boss + ".txt",
        boss : boss,
        success: function(sData){
            let temp = this.boss
            let div = document.getElementById(temp);
            //console.log(temp) logs "first" on the console
            let img = document.createElement("img");    
            let text = document.createElement('td1');
            img.src = "images/" + temp + ".jpg";
            img.alt = temp
            div.appendChild(img)  
            div.appendChild(text)

编辑2:代码执行的图像

https://imgur.com/a/WkYTn

2 个答案:

答案 0 :(得分:0)

试试这个Code Pen Example 。我认为你的问题在于&#34;变量&#34;以及如何为其分配价值。

  <div id = "first" style="border:1px red solid"></div>
    <div id = "second" style="border:blue"></div>
<div id = "third" style="border:green"></div>
    <script>
//try changing the value of condtion
var condition=3;
var variable="";
var img = document.createElement("img");   
//var text = document.createElement('td1');
img.src = "https://www.w3schools.com/w3images/fjords.jpg";
img.alt = "boss"
//div.appendChild(img) 

if (condition==1) variable = "first"
else if (condition==2) variable = "second"
else variable = "third"
console.log(img)
document.getElementById(variable).appendChild(img);
    <script>

答案 1 :(得分:0)

您的代码看起来正确!但是,我认为问题是,您在呈现DOM之前加载Javascript(例如,您正在<head>中加载脚本)。所以javascript无法找到div ..

&#13;
&#13;
var variable= "second";
var boss = "boss_baby";
let div = document.getElementById(variable);
console.log(variable) //logs "first" on the console
let img = document.createElement("img");    
let text = document.createElement('td1');
img.src = "images/" + boss + ".jpg";
img.alt = boss
div.appendChild(img)  
div.appendChild(text)
&#13;
#first, #second, #third {
display:block;
border: 1px solid blue;
height: 50px;
width: 200px;
margin : 10px;
}
&#13;
<div id = "list" class = "center"> Listing <br><br>
    <div id = "first"></div>
    <div id = "second"></div>
    <div id = "third"></div>
</div>
&#13;
&#13;
&#13;

要解决此问题,您可以在正文标记结束前加载<script> </body>

或在onload方法

中添加所有脚本
window.onload = function() {
// all your JS code goes here
}

OR

document.onload = function() {
// all your JS code goes here
}

问题编辑后:

您的代码看起来正确!但是,现在我怀疑当您从ajax获得响应时,您尝试访问的元素可能已被删除。