【问题标题】:Why does append.Child return me null when I use it in a Div but works when I put it on the body?为什么当我在 Div 中使用 append.Child 时它会返回 null,但当我将它放在身体上时会起作用?
【发布时间】:2018-04-04 22:35:05
【问题描述】:

由于某种原因,我的代码不起作用。当我尝试查看控制台将返回什么时,它会在返回时给我想要的答案:“未捕获的 TypeError:无法读取属性 'appendChild' of null”当我对 Div 进行同样的操作时。

这是我的代码,请帮助我...

function addOnePropertie () {
    var theUl = document.createElement ("UL");
    var theText = document.createTextNode ("This is a paragraph.");
    theUl.appendChild (theText);
    document.getElementById('theUlDiv').appendChild (TheUl); 
}

<div class="divOne">
    <header>
        Sign Up an Object
    </header>

    <ul>
        <span class="spanObject"> Name of Object: </span>
        <input placeholder="Type any Name...">
    </ul>
        <hr class="inDiv">
    <ul>
        <span class="spanObject"> Name plus Value of Propertie One: </span>
        <input class="smallInput" placeholder="Name of Propertie..."> 
        <input class="smallInput" placeholder="Value of Propertie">
    </ul>
    <div id="theUlDiv">
    </div>
    <button class="addPropertie" onclick="addOnePropertie ();">
        Add a Propertie 
        <i class="material-icons" style="color: blue; font-size: 15px;"> 
            note_add 
        </i>
    </button>
</div>

如您所见,如果我 console.log (theUl) 它返回了我想要的新 Ul 元素,如果我尝试将它放入 document.body.appendChild (theUl) 中也是如此,但如果我在 div 中这样做它不起作用,请帮助我出去了:D

【问题讨论】:

  • 为什么要尝试将纯文本直接放到&lt;ul&gt;
  • HTML 中的目标 div 有 theUlDiv 类,但您尝试通过 id 找到它
  • 是的,这是我的一个非常愚蠢的错误,看不到 class 而不是 id 但即便如此,它返回给我的却是完全相同的东西...... null 并且不起作用!
  • 将你的函数定义更改为window.addOnePropertie = function () {,然后用变量命名修复一些错误,然后它就可以工作了

标签: javascript html css append appendchild


【解决方案1】:

调试方法是,尝试在浏览器控制台中查询元素document.getElementById('theUlDiv'),您会发现它将返回 null,因为您的标记没有带有 id='theULDiv' 的元素,或者使用 @ 987654323@ 或更改您的标记以将id 添加到元素中。 编辑: 这行 .appendChild (TheUl); 在 appendChild 方法中还有另一个错误,您正在传递一个未定义的变量。你的实际变量是theUl,但你有大写的'T'

【讨论】:

  • 是的,这是我的一个非常愚蠢的错误,看不到 class 而不是 id 但即便如此,它返回给我的却是完全相同的东西...... null 并且不起作用!
  • 这行 .appendChild (TheUl); 在 appendChild 函数中还有另一个错误,您正在传递一个未定义的变量。你的实际变量是theUl,但你有大写'T'
  • 非常感谢,这解决了问题:D 一直错过拼写,哈哈,有时我真傻:D
【解决方案2】:

因为在您的 html 中没有 id 是“theUlDiv”的元素。

【讨论】:

  • 是的,这是我的一个非常愚蠢的错误,看不到 class 而不是 id 但即便如此,它返回给我的却是完全相同的东西...... null 并且不起作用!
猜你喜欢
  • 2021-08-24
  • 1970-01-01
  • 2021-06-19
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 2017-06-02
  • 1970-01-01
相关资源
最近更新 更多