Patrick Keane
Patrick Keane

Reputation: 673

Why cant read property 'style' of null in JavaScript?

I keep getting stuck on this javascript error! All I want to do is edit two values for CSS properties when a button is clicked. I keep getting this error:

Uncaught TypeError: Cannot read property 'style' of null

It occurs on the first document.getElementById line (below).

I've added the JavaScript in the footer of the page, but have also trialed in other positions, so don't know why it can't pick up the element.

HTML:

<a id="loadForm" href="">LINK</a>
<div id="FormContainer">
    <!-- CONTENT -->
</div>

JavaScript:

$(document).ready(function () {

    jQuery('#loadForm').on('click', function (e) {
        e.preventDefault();
        document.getElementById('#FormContainer').style.display = 'block';
        document.getElementById('#FormContainer').style.visability = 'visible';  
    })
});

Upvotes: 0

Views: 5087

Answers (2)

dan-lee
dan-lee

Reputation: 14502

Remove the leading hash from your argument to document.getElementById, as it is not part of the ID:

document.getElementById('FormContainer')

document.getElementById('#FormContainer') returns null. And you can't change the property style of null, because null is a primitive value and has no properties.

Or as you are already using jQuery just do:

$('#FormContainer').toggle(); // toggles visibility

Upvotes: 2

isJustMe
isJustMe

Reputation: 5470

you are using Jquery already, might as well go with:

$(document).ready(function () {

    jQuery('#loadForm').on('click', function (e) {
        e.preventDefault();
        $('#FormContainer').show();
    })
});

Upvotes: 2

Related Questions