Why am I getting “Cannot set property 'innerHTML' of null at ahint”

点点圈 提交于 2021-02-11 05:16:32

问题


I have tried to write some code in JS but, when I hover my mouse, the error "Cannot set property 'innerHTML' of null at ahint" is seen. I have read that such an error can occur because Chrome compiles/renders the JS code before the Div is even created. Therefore, I have put it on the bottom to check it. Unfortunately, putting it on the bottom has not solved my problem. Maybe someone more experienced will understand it.

var hint = "Hello";

function ahint()
{
    document.getElementById('#randomhint').innerHTML = hint;
}

    <div id="randomhint" onmouseover="ahint()">!</div>

    <script type="text/javascript" src="main.js"></script>
</body>

回答1:


Remove the # from the identifier:

var hint = "Hello";

function ahint()
{
    document.getElementById('randomhint').innerHTML = hint;
}

You have likely seen the # in code that uses jQuery or a similar library, as in $('#randomhint'). That’s how those libraries know that you mean to use an id and not, say, a tag name.

But you do not need (and cannot use) it when using getElementById (which is part of “vanilla” JavaScript). With getElementById, only the actual id value ("randomhint") belongs there.



来源:https://stackoverflow.com/questions/54554975/why-am-i-getting-cannot-set-property-innerhtml-of-null-at-ahint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!