File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -115,6 +115,7 @@ class HTMLElement{
115115 this removeWhitespace()
116116 Node[] querySelectorAll(string selector)
117117 Node querySelector(string selector)
118+ boolean matches(string selector)
118119 HTMLElement[] getElementsByTagName(string tagName)
119120 Node closest(string selector)
120121 Node appendChild(Node node)
@@ -209,6 +210,10 @@ Note: Full range of CSS3 selectors supported since v3.0.0.
209210
210211Query CSS Selector to find matching node. ` null ` if not found.
211212
213+ ### matches(selector)
214+
215+ Tests whether the node matches a given CSS selector.
216+
212217### getElementsByTagName(tagName)
213218
214219Get all elements with the specified tagName.
Original file line number Diff line number Diff line change 1- import { selectAll , selectOne } from 'css-select' ;
1+ import { is , selectAll , selectOne } from 'css-select' ;
22import he from 'he' ;
33import arr_back from '../back' ;
44import Matcher from '../matcher' ;
@@ -498,6 +498,18 @@ export default class HTMLElement extends Node {
498498 } ) ;
499499 }
500500
501+ /**
502+ * Tests whether the node matches a given CSS selector.
503+ * @param {string } selector Simplified CSS selector
504+ * @return {boolean }
505+ */
506+ public matches ( selector : string ) : boolean {
507+ return is ( this as HTMLElement , selector , {
508+ xmlMode : true ,
509+ adapter : Matcher ,
510+ } ) ;
511+ }
512+
501513 /**
502514 * find elements by their tagName
503515 * @param {string } tagName the tagName of the elements to select
Original file line number Diff line number Diff line change @@ -789,6 +789,23 @@ describe('HTML Parser', function () {
789789 root . children . length . should . eql ( 3 ) ;
790790 } ) ;
791791 } ) ;
792+
793+ describe ( '#matches' , ( ) => {
794+ it ( '`HTMLElement` should match CSS selector' , ( ) => {
795+ const html = parseHTML ( `<div class="example-class" data-test="example-data" id="example-id"></div>` ) ;
796+ html . firstChild . matches ( '.example-class' ) . should . be . true ( ) ;
797+ html . firstChild . matches ( '#example-id' ) . should . be . true ( ) ;
798+ html . firstChild . matches ( 'div' ) . should . be . true ( ) ;
799+ html . firstChild . matches ( '[data-test="example-data"]' ) . should . be . true ( ) ;
800+ } ) ;
801+ it ( '`HTMLElement` should not match CSS selector ' , ( ) => {
802+ const html = parseHTML ( `<div></div>` ) ;
803+ html . firstChild . matches ( '.no-match' ) . should . be . false ( ) ;
804+ html . firstChild . matches ( '#no-match' ) . should . be . false ( ) ;
805+ html . firstChild . matches ( 'span' ) . should . be . false ( ) ;
806+ html . firstChild . matches ( '[data-test="no-match"]' ) . should . be . false ( ) ;
807+ } ) ;
808+ } ) ;
792809 } ) ;
793810
794811 describe ( 'stringify' , function ( ) {
You can’t perform that action at this time.
0 commit comments