Home > Blockchain >  Ignore a line of Javascript if the element isn't present on the page and skip to the next line?
Ignore a line of Javascript if the element isn't present on the page and skip to the next line?

Time:12-03

Working on a django web app and running into an issue with my javascript. The web application is multiple different html pages, so the elements my js code is searching for are present on some pages but not others. If the second line is not present on the current page, the script stops running and the final function will not work. I have a "plan" page where you can add additional tags to your plan and then a separate page to filter results. If I'm on the plan page then the "#filterBtn" element is not present so my createNewTagField function doesn't work. If I switch the two lines of code, the opposite happens. I can't get them both to work since the elements javascript is searching for are on two different pages and not present at the same time.

These are the lines causing problems.

document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('#mobile-menu').onclick = toggleMobileMenu;
    document.querySelector('#filterBtn').onclick = toggleFiltersMenu;
    document.querySelector('#addTag').onclick = createNewTagField;
    
});

I've rearranged the lines of code and it just fixes it for one page while still having the problem on the other page. I'm thinking it needs to be something like if null then continue to the next line, but haven't been able to find the right code from my searching.

CodePudding user response:

If you do not have more than a couple tags/lines it's I would use the try-catch statement to ignore a line of code if the element isn't present on the page:

try {
// This line of code may throw an error if the element is not found
const element = document.querySelector('.my-element');
// Do something with the element...
} catch (error) {
// If an error is thrown, ignore it and continue with the next line
console.log(error); // Output: Error: The element is not found
}

// This line of code will be executed even if the element is not found
console.log('Element not found. Trying again')

Do this for each of the scenarios.

CodePudding user response:

You can check for truthiness in JavaScript. https://developer.mozilla.org/en-US/docs/Glossary/Truthy

Because the absence of an element in the DOM will result in null, this works pretty well, and it's highly readable.

document.addEventListener('DOMContentLoaded', function() {
    
    const mobileMenu = document.querySelector('#mobile-menu');
    const filterBtn = document.querySelector('#filterBtn');
    const addTag = document.querySelector('#addTag');

    if (mobileMenu) mobileMenu.onclick = toggleMobileMenu;
    if (filterBtn) mobileMenu.onclick = toggleFiltersMenu;
    if (addTag) mobileMenu.onclick = createNewTagField;
    
});
  • Related