How can I check if an element exists in the DOM using JavaScript?

I’ve been working with DOM manipulation for a while, and one of the most straightforward ways to check if an element exists in the DOM is by using document.querySelector(). Unlike getElementById(), this method is more flexible because you can select elements using any CSS selector. Plus, it returns null if the element isn’t found, which makes it super easy to check if it exists.

Solution:

window.onload = function() {
    var element = document.querySelector("#demo");
    if (element) {
        console.log("Element exists");
    } else {
        console.log("Element does not exist");
    }
};

This solution is clean and works great for single elements. You can even adjust the selector for more complex queries.