Uncaught TypeError: Cannot read property 'style' of null - JS error

47,808

Solution 1

Don't place the hash in id (#):

document.getElementById('iframetest')

As per your comment, you can do like this:

function select()
{
   document.getElementById('iframetest').style.display = 'block' ? 'none' : 'block';
}

Solution 2

Move your JS below the HTML.

<iframe src="localhost/createaclass" id="iframetest"></iframe>
<div class="b" onclick="select()">

<script>
  function select()
  {
    document.getElementById('#iframetest').style.display='block';
  }
</script>

Solution 3

Maybe too late to answer it. But your selector is returning null because at this line

document.getElementById('#iframetest').style.display='block';

You need to change it to:

document.getElementById('iframetest').style.display='block';

When you specify getElementById, then your JS will directly go to the element with the id of 'iframetest'. There is no need of '#'.

Share:
47,808
user3818791
Author by

user3818791

Working for Intel.

Updated on July 25, 2022

Comments

  • user3818791
    user3818791 almost 2 years

    I'm getting a javascript error from my console that reads:

    Uncaught TypeError: Cannot read property 'style' of null

    Does anyone know whats wrong?

    Code (JS):

    <script>
        function select()
        {
            document.getElementById('#iframetest').style.display='block';
        }
    
    </script>
    

    Code (HTML):

    <iframe src="localhost/createaclass" id="iframetest"></iframe>
    
    <div class="b" onclick="select()">
    
  • user3818791
    user3818791 over 9 years
    I would like the element to be hidden and show on click, however the element shows anyway. Any suggestions? :) Thank you by the way
  • Mritunjay
    Mritunjay over 9 years
    @user3818791 For that you can say <iframe src="localhost/createaclass" id="iframetest" style="display:none"></iframe>
  • user3818791
    user3818791 over 9 years
    I've already stated within my framework, it still shows regardless
  • Mritunjay
    Mritunjay over 9 years
    there should be document.getElementById('iframetest').style.display == 'block' , fix that. you are assigning.
  • user3818791
    user3818791 over 9 years
    #iframetest { display:none; }That is my CSS but its still automatically showing.