Javascript、getElementById 和样式不起作用:未捕获的类型错误:无法读取 null 的属性“样式”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19417866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:30:48  来源:igfitidea点击:

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

javascriptcsssyntax

提问by user1269625

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

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

采纳答案by Todd

Should be:

应该:

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

回答by Hanky Panky

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

那只是意味着在执行该 JavaScript 时

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

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

这要么意味着success您的文档中没有带有 id 的元素,要么到目前为止还没有加载。在加载后移动要调用的 Javascript。

回答by Aditya Vikas Devarapalli

that means

这意味着

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

情况 1:您的 javascript 代码在具有该 id 的元素加载到该页面之前被执行,或者

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

情况 2:您的文档中不存在具有此类 ID 的元素

if your problem is case 1:

如果您的问题是情况 1:

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

尝试将 javascript 代码放在结束</body>标记之前

if it's case 2:

如果是情况 2:

try changing the idof the element in the lines

尝试更改行id中元素的

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

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

将 更改id'success'为其他id实际存在的

回答by Ricky Wilson

I would suggest using jQuery for this

我建议为此使用 jQuery

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

回答by PSR

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

Element does not exist with id success

元素不存在 id success