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

1

The JS DOM below is for modifying through classes, the styles of two elements that are dynamically created in the document. But it is not always that these elements will appear in the document. Maybe they show up, maybe not. When they are, the code works fine, and when they are not, the console returns TypeError: jsNavButton is undefined . How do I prevent this?

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

    
asked by anonymous 01.07.2018 / 17:33

1 answer

2

Verify that the elements exist with if . If the element does not exist, nothing is done and does not return 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";
}
    
01.07.2018 / 17:43