-2

So, I was just trying to make a <div> appear on an onkeyup event with javascript and for some reason, it didn't let me do it and I got the error:

Uncaught TypeError: Cannot read property 'style' of null

This is my code:

HTML:

<div class="content" id="content" style="display: none">

Javascript:

function showContent() {
    document.getElementById('content').style.display = 'block';
}

Can you please help? Thanks.

Yash
  • 11,486
  • 4
  • 19
  • 35
ArchiPlays
  • 71
  • 6
  • 3
    If `showContent()` is called before the element is part of the DOM, you'd get that exact error. – Pointy Oct 10 '19 at 15:17
  • 2
    Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Heretic Monkey Oct 10 '19 at 15:20
  • check out the `defer` attribute for [script elements](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script). You can do this instead of having to put your scripts at the end. – Mason Oct 10 '19 at 15:30
  • @Pointy I was using a different file but I moved it to the HTML. Now I don't get the error but it doesn't work and it doesn't change the style. – ArchiPlays Oct 10 '19 at 15:30

1 Answers1

1

I guess your function is called before your block "content" is added to DOM.

You may want to wait for the DOM to be ready before calling your function, or call it from a button as following:

function showContent() {
  document.getElementById('content').style.display = 'block';
}
.content {
  width: 200px;
  height: 100px;
  background: red;
}
<button onClick="showContent()">Show Block</button>

<div class="content" id="content" style="display: none">
Fire Druid
  • 246
  • 2
  • 9