简体   繁体   中英

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. Been searching for solutions, but most of them are either replacing the missing ID or putting information into an already existing one. I just want my script to be "okay" with the fact that certain ID's will not be found.

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.

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.

Hopefully someone can help!

Try something like this:

Check if the element with that ID exists first.

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. You could avoid some repetition (and fetching twice the id within DOM):

 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM