There are various DOM selector like querySelector , querySelectorAll, getElementById, getELementsByClassName and many more. But my question is when and where we should use which selector during programming. Are there any best practices that tells to specifically use the selector for this task.
querySelector returns one (the first) element found, and uses a CSS style selector.
querySelectorAll returns a node list (which, depending on your browser support, you may need to convert to an array to work with), and uses the same CSS style selector.
getElementById takes a string and only finds an element that matches that ID (IDs should be unique).
getElementsByClassName takes a string and matches like ID, but can return an array like list of elements.
If you're familiar with CSS selectors, you can use querySelector and querySelectorAll for almost every situation. The performance is pretty close to the getElement* ones, but they're much more powerful. For example, if you wanted to get a span that is the first child of a class in an id, you could do .querySelector('#id .class span') instead of chaining together .getElementById('id').getElementsByClass('class')[0].getElementsByTagName('span')[0].
I don't think there's any specific rules on what to use when but I'll share my opinions regarding each method:
querySelector but for multiple elementscaniuse.com is a great resource to check browser support.