I have javascript/Jquery files like this that is suppose to store javascript and Jquery functions for my entire website.
Issue: All the functions ID are not present in all the pages, so the script doesn't work and it stops at the line where it can't find ID reference and throw this error "Cannot set properties of null (setting 'innerHTML')"
This is an example that represents what the script flow
//Code for page 1
var page1redirect = document.getElementById("page1redirectafter").value;
document.getElementById("page1redirectID").value = page1redirect;
//Code for page 2
var page2redirect = document.getElementById("page2redirectafter").value;
document.getElementById("page2redirectID").value = page2redirect;
//Code for page 3
var page3redirect = document.getElementById("page3redirectafter").value;
document.getElementById("page3redirectID").value = page3redirect;
Is there any way I can skip or ignore any error that doesn't run and continue the next function?
CodePudding user response:
If the id
s are correct and included in the HTML, those objects are probably null
since by the time the script runs the DOM has still not been fully loaded. So you might want to delay the script, try more than once or ask the browser to inform you of any changes made to the DOM.
If you just want to ignore it when an object is null
and do nothing, just check if it's null
:
Instead of e.g.
var page3redirect = document.getElementById("page3redirectafter").value;
document.getElementById("page3redirectID").value = page3redirect;
Do
var page3redirect = document.getElementById("page3redirectafter");
if (page3redirect != null) {
var page3redirectID = document.getElementById("page3redirectID");
if (page3redirectID != null) {
page3redirectID.value = page3redirect.value;
};
};