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>
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.
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.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With