Uncaught TypeError: Cannot set property 'visibility' of undefined code example

Example 1: error Cannot set property 'visibility' of undefined

document.getElementsByClassName("targ").forEach(e => e.style.visibility = "hidden");

Example 2: error Cannot set property 'visibility' of undefined

function openNav() {
  // document.getElementById("mySidenav").style.width = "250px";
  targList = document.getElementsByClassName("targ");
  document.getElementsByClassName("targ")
  if (targList) {
    for (var x = 0; x < targList.length; x++) {
      targList[x].style.visibility = "hidden";
    }
  }
  document.getElementById("targimg").style.textAlign = "center";
}