Many of us have encountered the problem of choosing which selector to use from the list of JavaScript selectors. Using the right selector can solve enormous amount of problem and can make the code readable and clean.
To get a clear glimpse of how to use the selectors, let us take a look at what all these selectors are and what is their functionality -
document.getElementById() :
This selector returns only one element with a specified Id. Also as we know that only one element can poses a specific Id, so the latter is obvious.
syntax - document.getElementById("main_item-Id");
There is no requirement to add "#" before mentioning the Id of the element in this selector.
document.getElementsByClassName() :
This one returns a HTML Collection of all the elements having the specified class as that mentioned in the selector. Notice the "s" after element, it represents the same thing.
syntax - document.getElementsByClassName("specified_class_name");
The dot(.) class specifier is not added before class name in this selector.
document.getElementsByTagName() :
This selector also return an array like format HTML Collection of all elements which have the same tag name as the one specified inside the double quotes(""). Like all the selectors which return a collection/multiple elements, it searches from top to bottom in the html file for the list of elements.
syntax - document.getElementsByTagName("element-tag-name");
It works for all the html elements like p,div,section etc.
document.querySelector() :
This selector only returns the first element matching the query specified in it.
syntax - document.querySelector("tag/class/id");
It should be noted that it is required to add the class specifier(.) or id specifier(#) in this selector.
document.querySelectorAll() :
As the name suggests it returns the list of all elements or which can be called an HTML Collection that match the condition in it.
syntax - document.querySelectorAll("tag/class/id");
Just like querySelector, class specifier(.) and id specifier(#) are mandatory to be added before name in this selector.
For more detailed insight about these selectors one can visit the mdn docs.
Comments
Post a Comment