[英]Want JS to continue if ID (document.getElementById) isn't found
I'm trying to make a javascript just "ignore" a missing div-id and keep running down the lines. 我正在尝试制作一个JavaScript,只是“忽略”缺少的div-id并继续运行。 Been searching for solutions, but most of them are either replacing the missing ID or putting information into an already existing one.
一直在寻找解决方案,但是大多数解决方案要么替换丢失的ID,要么将信息放入已经存在的ID中。 I just want my script to be "okay" with the fact that certain ID's will not be found.
我只希望我的脚本“正常”,因为不会找到某些ID。
var Info01 = `Some text`;
document.getElementById("Info01").innerHTML = Info01;
var Info02 = `Some other text`;
document.getElementById("Info02").innerHTML = Info02;
If the div-id "Info01" isn't present, I want it to just be cool with that and do the next line and so on. 如果不存在div-id“ Info01”,我希望它很酷,然后执行下一行,依此类推。
I've been trying some if-statements, but I'm just not good enough to figure it out by myself and google isn't providing me with the solution I'm looking for. 我一直在尝试一些if语句,但我不足以让我自己弄清楚它,而google并没有为我提供所需的解决方案。
Hopefully someone can help! 希望有人可以提供帮助!
Try something like this: 尝试这样的事情:
Check if the element with that ID exists first. 检查具有该ID的元素是否首先存在。
var Info01 = "Some text";
if(document.getElementById("Info01")) {
document.getElementById("Info01").innerHTML = Info01;
}
var Info02 = "Some other text";
if(document.getElementById("Info02")) {
document.getElementById("Info02").innerHTML = Info02;
}
Going a bit further with Zachary McGee's answer. Zachary McGee的答案再进一步一点。 You could avoid some repetition (and fetching twice the id within DOM):
您可以避免重复(并在DOM中获取两次ID):
const info01 = "Some text" const info02 = "Some other text"; const setText = (id, content) => { const item = document.getElementById(id) if (item === null) return item.innerText = content } setText("Info01", info01) setText("Info02", info02)
<div id="Info02"></div>
Also not that I am using .innerText
rather than .innerHTML
, since the former is sufficient for the needs of your question and the latter is subject to XSS . 同样不是我使用
.innerText
而不是.innerHTML
,因为前者足以满足您的问题,而后者则受XSS的约束 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.