Edvard Åkerberg
Edvard Åkerberg

Reputation: 2191

javascript: getElementById is not finding element

Explain to my why this works when I click the button.

<script type="text/javascript">
  function myFunction() {
    if (screen.width <= 800) {
      document.getElementById('cover-img').style.display = 'none';
    }
  }
</script>
<input type="submit" onclick="myFunction()">

While this does not:

<script type="text/javascript">
  if (screen.width <= 800) {
    document.getElementById('cover-img').style.display = 'none';
  }
</script>

It returns the error:

Uncaught TypeError: Cannot read property 'style' of null

Upvotes: 0

Views: 1541

Answers (2)

Andrew Bone
Andrew Bone

Reputation: 7291

Here are 2 examples to better explain it:

In this example the JS is at the top so is ran before I make the div with the ID cover-img. Meaning when it is ran the getElementById returns 0 results, giving the error Cannot read property 'style' of null"

<script type="text/javascript">
  document.getElementById('cover-img').style.display = 'none';
</script>
<div id="cover-img">I'm still alive!</div>
<div>I'll be here not matter what...</div>

In this example however I've moved the script to after the cover-img div is created meaning getElementById has a result that can be passed to style.

And as you'll see the div is hidden.

<div id="cover-img">I'm still alive!</div>
<div>I'll be here not matter what...</div>
<script type="text/javascript">
  document.getElementById('cover-img').style.display = 'none';
</script>

I hope that makes sense, I took the size bit out just to make it clearer but the same holds true with that in place.

That being said using CSS to achieve this is a much better solution as @Foker points out in another answer on this page.

Upvotes: 0

Foker
Foker

Reputation: 1011

you can do that with pure css

@media(max-width:75em){
    #mydiv{
        display:none;
    }
}

Upvotes: 3

Related Questions