How do you check if the result of querySelectorAll() is empty?
Answers:
In JavaScript, when you use
querySelectorAll(), it returns aNodeListof elements that match the specified CSS selector. If no elements match, theNodeListwill be empty, but it is important to note that an emptyNodeListis still an object. To check if it is empty, you can use thelengthproperty of the returnedNodeList.Here’s how you can check if the result of
querySelectorAll()is empty:const elements = document.querySelectorAll('your-selector-here'); if (elements.length === 0) { console.log('No elements found'); } else { console.log('Elements found:', elements); }Replace
'your-selector-here'with the CSS selector you want to use. Ifelements.lengthis0, it means that no elements matched your query, and hence the result is considered empty.