0

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!

David Thomas
  • 249,100
  • 51
  • 377
  • 410
eskilla
  • 7
  • 4

2 Answers2

3

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;
}
Zachary McGee
  • 504
  • 1
  • 4
  • 16
  • 1
    I'm a bit of a stickler for strictness because it helps you understand what is going on. `getElementById` will return `null` when it can't find the element so the correct (strict) condition is `if (document.getElementById("Info01") === null) {`. You're also missing the `.innerHTML` property in your assignment. – Halcyon Aug 08 '19 at 23:27
  • 2
    Thanks @Halcyon, you are right, I did not have time to test. – Zachary McGee Aug 08 '19 at 23:45
  • 1
    @ZacharyMcGee you should just assign the `document.getElementById('Info01')` to a variable in order to not have the javascript have to compute it twice. – Fallenreaper Aug 08 '19 at 23:47
  • @Fallenreaper you are right also, OP would be best to follow the other answer. I was just attempting to follow their original syntax. – Zachary McGee Aug 09 '19 at 00:08
3

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.

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82