@@ -6,7 +6,7 @@ import { isString } from './is';
66 * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]
77 * @returns generated DOM path
88 */
9- export function htmlTreeAsString ( elem : unknown ) : string {
9+ export function htmlTreeAsString ( elem : unknown , keyAttr ?: string ) : string {
1010 type SimpleNode = {
1111 parentNode : SimpleNode ;
1212 } | null ;
@@ -28,7 +28,7 @@ export function htmlTreeAsString(elem: unknown): string {
2828
2929 // eslint-disable-next-line no-plusplus
3030 while ( currentElem && height ++ < MAX_TRAVERSE_HEIGHT ) {
31- nextStr = _htmlElementAsString ( currentElem ) ;
31+ nextStr = _htmlElementAsString ( currentElem , keyAttr ) ;
3232 // bail out if
3333 // - nextStr is the 'html' element
3434 // - the length of the string that would be created exceeds MAX_OUTPUT_LEN
@@ -54,7 +54,7 @@ export function htmlTreeAsString(elem: unknown): string {
5454 * e.g. [HTMLElement] => input#foo.btn[name=baz]
5555 * @returns generated DOM path
5656 */
57- function _htmlElementAsString ( el : unknown ) : string {
57+ function _htmlElementAsString ( el : unknown , keyAttr ?: string ) : string {
5858 const elem = el as {
5959 tagName ?: string ;
6060 id ?: string ;
@@ -74,16 +74,22 @@ function _htmlElementAsString(el: unknown): string {
7474 }
7575
7676 out . push ( elem . tagName . toLowerCase ( ) ) ;
77- if ( elem . id ) {
78- out . push ( `#${ elem . id } ` ) ;
79- }
8077
81- // eslint-disable-next-line prefer-const
82- className = elem . className ;
83- if ( className && isString ( className ) ) {
84- classes = className . split ( / \s + / ) ;
85- for ( i = 0 ; i < classes . length ; i ++ ) {
86- out . push ( `.${ classes [ i ] } ` ) ;
78+ const keyAttrValue = keyAttr ? elem . getAttribute ( keyAttr ) : null ;
79+ if ( keyAttrValue ) {
80+ out . push ( `[${ keyAttr } ="${ keyAttrValue } "]` ) ;
81+ } else {
82+ if ( elem . id ) {
83+ out . push ( `#${ elem . id } ` ) ;
84+ }
85+
86+ // eslint-disable-next-line prefer-const
87+ className = elem . className ;
88+ if ( className && isString ( className ) ) {
89+ classes = className . split ( / \s + / ) ;
90+ for ( i = 0 ; i < classes . length ; i ++ ) {
91+ out . push ( `.${ classes [ i ] } ` ) ;
92+ }
8793 }
8894 }
8995 const allowedAttrs = [ 'type' , 'name' , 'title' , 'alt' ] ;
0 commit comments