Utilizing Document.querySelector()
The method Document
known as querySelector() is responsible for fetching the initial WebElement within the document that corresponds to the specified selector, or group of selectors. In case no matches are identified, a result of null
will be produced.
Note: The matching operation occurs through depth-first pre-order traversal of
the nodes in the document starting from the first element in the document's
markup and progressing through sequential nodes based on the number
of child nodes.
Syntax:
element = document.querySelector(selectors);
Employing Document.querySelectorAll()
The method Document
referred to as querySelectorAll() delivers a static NodeList presenting a list of the elements within the document that correspond to the specified set of selectors.
Note: Despite NodeList
not being an Array
, it is feasible to
iterate over it utilizing forEach()
. It can also undergo conversion into a genuine
Array
utilizing Array.from()
. Nonetheless, certain older browsers have yet to implement NodeList.forEach()
or even Array.from()
. This challenge
can be overcome by leveraging Array.prototype.forEach()
.
Syntax:
elementList = parentNode.querySelectorAll(selectors);
Application of CssSelector
In scenarios where xpath or css-selectors are utilized, a compilation of the document's elements corresponding to the specified set of selectors is produced.
Summary
To synopsize, if you opt for using querySelector()
, solely the primary matched element is retrieved. For cases requiring rendering all matched elements, opting for querySelectorAll()
is necessary as illustrated below:
document.querySelector("div[slot^='Learner']>div>div>span")