1

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>
elixenide
  • 44,308
  • 16
  • 74
  • 100
  • I have edited your answer for idiom. However, to what the pronoun *it* refers in "I have put **it** on the bottom" remains unclear to me. You might edit that. – thb Feb 06 '19 at 13:50
  • If you read the docs for `getElementById` you'll see your mistake. – Asons Feb 06 '19 at 13:55
  • Does this answer your question? [Why does \`document.getElementById(“#datepicker1”)\` not find my element?](https://stackoverflow.com/questions/33036800/why-does-document-getelementbyid-datepicker1-not-find-my-element) – Sebastian Simon Jul 06 '20 at 04:57
  • Related: [When to use # symbol to get object in JavaScript](https://stackoverflow.com/q/15486154/4642212). – Sebastian Simon Jul 06 '20 at 04:57

1 Answers1

3

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.

elixenide
  • 44,308
  • 16
  • 74
  • 100
  • Thanks, can you maybe explain why the caused the problem? – Mateusz Dettlaff Feb 06 '19 at 13:45
  • Edge case for a _typo_ question, still, also _vanilla_ javascript can use `#id`, e.g. `querySelector` – Asons Feb 06 '19 at 13:53
  • @LGSon It is, of course, a kind of typo. But some typo questions are valid when they are about the logic and syntax of the language, as opposed to pure errors like `getEEElementById`. And I didn’t mean to imply that vanilla JavaScript never uses `#` in this way; I’ve edited my answer to clarify. – elixenide Feb 06 '19 at 14:04
  • 1
    Great..and understood that, hence I wrote _edge case_ :) – Asons Feb 06 '19 at 14:41