Prevent Undefined of elements that may or may not appear in the document

Asked

Viewed 20 times

1

The JS DOM below is to modify through the classes, the styles of two elements that are created dynamically in the document. But it’s not often that these elements will appear in the document. Maybe they do, maybe they don’t. When they are, the code works fine, and when they are not, the console returns TypeError: jsNavButton is undefined. How to avoid this?

var jsNavButton = document.querySelectorAll(".js-nav-toggle")[0], jsNavHidden = document.querySelectorAll(".js-nav-hidden")[0]; jsNavButton.style.backgroundColor = "tomato"; jsNavHidden.style.backgroundColor = "blue";

1 answer

2


Check if elements exist with if. If the element does not exist, nothing is done and returns no error:

var jsNavButton = document.querySelectorAll(".js-nav-toggle")[0],
   jsNavHidden = document.querySelectorAll(".js-nav-hidden")[0];

if(jsNavButton){
   jsNavButton.style.backgroundColor = "tomato";
}

if(jsNavHidden){
   jsNavHidden.style.backgroundColor = "blue";
}
  • Functional as always. Thx.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.