Call a function if an Element exists using JavaScript

avatar

Borislav Hadzhiev

Sun Jan 09 20222 min read

banner

Photo by Caleb Fisher

Call a function if an Element exists using JavaScript #

To call a function if an element exists:

  1. Use the getElementById or querySelector methods to select the element.
  2. Check if the stored value is not equal to null.
  3. If the condition is met, invoke the function.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box content</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
function sum(a, b) { return a + b; } // โœ… Select element by ID [getElementById] const el1 = document.getElementById('box'); if (el1 !== null) { console.log(sum(5, 55)); console.log('โœ… el1 exists'); } else { console.log('โ›”๏ธ el1 does NOT exist'); } // โœ… Select first element with class [querySelector] const el2 = document.querySelector('.my-class'); if (el2 !== null) { console.log(sum(5, 55)); console.log('โœ… el2 exists'); } else { console.log('โ›”๏ธ el2 does NOT exist'); }

In our first example, we used the document.getElementById method to select an element by id.

The method returns the element, whose id property matches the provided string.

If no element with the provided id exists in the document, a null value is returned.

Our if statement checks if the value stored in the el1 variable is not equal to null before calling the sum function.

The if block is only ran if the element exists, otherwise the else block runs.

In the second example we used the document.querySelector method to get the first element that matches the provided selector.

index.js
function sum(a, b) { return a + b; } // โœ… Select first element with class [querySelector] const el2 = document.querySelector('.my-class'); if (el2 !== null) { console.log(sum(5, 55)); console.log('โœ… el2 exists'); } else { console.log('โ›”๏ธ el2 does NOT exist'); }

The querySelector method takes a string that represents a valid CSS selector as a parameter.

If no elements match the selector, the method returns a null value just like the getElementById method.

Since there are no elements with a class of my-class on the page, the condition is not met and the else block runs.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee