Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.getElementbyId() returning null [duplicate]

Tags:

javascript

dom

In the code at the line marked as //Error in comments. I get Javascript error saying: "Cannot read property style of 'null'". I have no idea what it is not able to find the object. I have thought and tried everything. Please help. Here is the code:

<script type="text/javascript">

    $.getJSON('https://graph.facebook.com/647045111?fields=first_name&<%= Session["Token"] %>',

    function (data) {
        $('#userName').html(data.first_name);
    });

    document.getElementById('connectedUnregistered').style.display = 'block'; //Error

</script>

    <div id="userName"></div>

    <div id="disconnected" style="display:block;">

     <div id="heading">Facebook login</div> 

     <a href="Account/FacebookLogin" id="loginButton"><div id="fbConnectButton"><img src="/Content/Images/fbconnect.png"/></div></a>    

    </div>

     <div id="connectedUnregistered" style="display:none">

     <div id="heading">Register Now</div> 



    </div>
like image 280
Umair Khan Jadoon Avatar asked Aug 22 '11 18:08

Umair Khan Jadoon


People also ask

Why is my getElementById returning NULL?

This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.

What does the document getElementById () method return?

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.

What will method getElementById () return if nothing is found?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM.


2 Answers

You are executing your javascript code BEFORE the <div id="connectedUnregistered" /> was actually created.

Also note that you did not close your <div> with a corresponding </div>.

So move your javascript code to a part below your HTML. Or execute it after the page finished loading. If you are using JQuery you can do:

<script>

    $(document).ready(function() {

        ... your code ...

    });
</script>
like image 81
Jules Avatar answered Oct 12 '22 22:10

Jules


Put your script at the end of the HTML document instead of the beginning, and see if that solves things.

JavaScript can't edit the DOM element because it hasn't been created yet.

like image 34
Blazemonger Avatar answered Oct 12 '22 23:10

Blazemonger