admin管理员组

文章数量:1516870

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

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

Share Improve this question edited Oct 17, 2013 at 3:48 user1269625 asked Oct 17, 2013 at 3:42 user1269625user1269625 3,20926 gold badges81 silver badges113 bronze badges 1
  • are you running the script after the element is added to the dom? add the code to window load handler – Arun P Johny Commented Oct 17, 2013 at 3:43
Add a ment  | 

5 Answers 5

Reset to default 3

Should be:

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

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.

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

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

Element does not exist with id success

I would suggest using jQuery for this

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

本文标签: