In the simple terms
DOM is a representation of your HTML to the browser and allows you to manipulate the page.
DOM Selectors, as the name suggests is used to select HTML elements within a document using JavaScript. There are 5 ways in which you can select elements in a DOM using selectors. Following methods are properties of the document object-
- getElementsByTagName()
- getElementsByClassName()
- getElementById()
- querySelector()
- querySelectorAll()
getElementsByTagName
document.getElementsByTagName('h1')
returns a collection of items matching the tag name h1.
getElementsByClassName
document.getElementsByClassName('heading')
This method returns all the elements that matches the specified Class name.
querySelector
This one returns the first element that matches the specified CSS selector in the document. we can use all kinds of CSS selectors within the querySelector method that we will use in a normal CSS file. always mention ID by # and class by .(dot)
document.querySelector('.className')
document.querySelector('#Id')
querySelectorAll
This method returns all the elements that match the specified CSS selector in the document. no two elements should have the same Id
document.querySelectorAll('.className')
document.querySelectorAll('#Id')
getElementById
The selection is based on the Id name. And this seems to be similar to Tag name & Class name selector but there’s a difference in how many elements this selector selects. In all the above selectors, a list of all matching elements is returned. But this selector returns only the first matched element while ignoring the remaining.no two elements should have the same Id. It returns the element as soon as it gets a match. Also you can notice a difference in the name of the selector, the word element is singular in getElementById while it’s plural in other selectors.
document.getElementById('id')
- Difference between querySelectors and getElementById
The querySelector method lets you retrieve an element using a CSS selector query. The getElementById method retrieves an element by its DOM ID. getElementById is more restrictive than querySelector because you can only retrieve elements based on their particular ID. You would use getElementById method if you only want to retrieve one element from the web page. This is because HTML IDs must be unique to a particular element. You cannot use an ID to refer to two elements on the web page.
Both methods have wide browser support. You should opt to use the querySelector method if you need to select elements using more complex rules that are easily represented using a CSS selector. If you want to select an element by its ID, using getElementById is a good choice.
One last difference worth mentioning between the selectors is that querySelector is simply newer. All major browsers do support it however if you're using an older browser or a less supported one getElementById may be more suitable for your purposes