user1269625
user1269625

Reputation: 3209

Javascript, getElementById and style not working: Uncaught TypeError: Cannot read property 'style' of null

I have this code here:

document.getElementById('success').style.display("block");
document.getElementById('success').text("aaaa"); 

and I get this error, why?

Uncaught TypeError: Cannot read property 'style' of null 

<span id="success" style="color:#FFF; display:none;"></span>

I moved my code to bottom of the page and I get this new error now

Uncaught TypeError: Property 'display' of object #<CSSStyleDeclaration> is not a function

Upvotes: 5

Views: 27153

Answers (5)

Ricky Wilson
Ricky Wilson

Reputation: 3359

I would suggest using jQuery for this

 $("#success").css("display","block");
 $("#success").append("aaa");

Upvotes: -2

Todd
Todd

Reputation: 1674

Should be:

var elSuccess = document.getElementById('success');
elSuccess.style.display = 'block';
elSuccess.innerText = 'aaa';

Upvotes: 3

Aditya Vikas Devarapalli
Aditya Vikas Devarapalli

Reputation: 3473

that means

CASE 1: your javascript code is getting executed before the element with that id has loaded on that page or

CASE 2: no element in your document exists with such an id

if your problem is case 1:

try to place the javascript code just before the closing </body> tag

if it's case 2:

try changing the id of the element in the lines

document.getElementById('success').style.display("block");
document.getElementById('success').text("aaaa"); 

change the id 'success' to some other id that actually exists

Upvotes: 1

PSR
PSR

Reputation: 40318

if(document.getElementById('success') != null)
{
 ................................
}

Element does not exist with id success

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

That simply means that at the time of execution of that JavaScript

document.getElementById('success')  // is NULL

Which either means that there is no element with an id success in your document, or it has not loaded so far. Move the Javascript to be called after it has loaded.

Upvotes: 3

Related Questions