Reputation: 1825
I am writing code in plain JavaScript, there are lot of scenarios where I will use querySelector()
method, I ran into issue multiple times like
"Uncaught TypeError: Cannot read property 'classList' of null" for the following code,
document.querySelector('.tab.active').classList.remove('active');
/** Tab not available at the time**/
In Jquery $('.tab.active').removeClass('active');
will run only if the element is available without throwing error.
I want to achieve similar behavior in JavaScript. Please provide your ideas.
I am not willing to write three lines of code for every DOM operation I am doing, looking for one line code like Jquery.
var activeTab = document.querySelector('.tab.active');
if(activeTab !== 'null' ){
activeTab.classList.remove('active');
}
Upvotes: 3
Views: 946
Reputation: 371148
Explicitly checking for the existence of the element in your code as you're doing originally is surely the clearest way you could do it, but if you really don't want to, you could create your own function that, if no element is found, returns an object with methods that don't do anything. For example:
const customQS = selector => (
document.querySelector(selector)
|| {
classList: {
remove: () => void 0
}
}
);
customQS('.tab.active').classList.remove('active');
console.log('done, no error');
Of course, with that method, you'd have to create properties for each DOM method you'd want to use. A more robust option would be to actually create an element and return it, which would be more expensive, but the element will be garbage collected right afterward:
const customQS = selector => (
document.querySelector(selector)
|| document.createElement('div')
);
customQS('.tab.active').classList.remove('active');
console.log('done, no error');
Upvotes: 2