The matches() method checks if the Element that would be selected by the provided selectorString is the selector. If the specified element is the valid selector then it will return true, else false.
Syntax:
let boolean_result = element.matches("selector");
Parameters: Here, the selector is used as a parameter.
Return value: It returns Boolean value i.e. (True when the selector matches else false).
Example: In this example, there is a list in which there are some elements that have class selectors as numbers. So, we stored the list in a variable and by iterating on the list, if the selector matches the number class, then printed on the document correspondingly.
HTML
<!DOCTYPE html> < html > < head > < title > HTML DOM matches() Method </ title > </ head > < body > < h1 >neveropen</ h1 > < ul id = "abc" > < li >A</ li > < li class = "number" >1</ li > < li >C</ li > < li class = "number" >2</ li > </ ul > < script > let abc = document.getElementsByTagName('li'); for (let i = 0; i < abc.length ; i++) { if (abc[i].matches('.number')) { document.write(abc[i].textContent + ' is not an alphabet , '); } } </script> </ body > </ html > |
Output:
Note: It is supported by all browsers.