From 31d44ba14189f7cb0b68aed0720a7b8d0477b504 Mon Sep 17 00:00:00 2001 From: Mike Plummer Date: Wed, 17 Jan 2024 09:23:20 -0600 Subject: [PATCH] feat: Allow preferring `name` attr independently --- src/getName.js | 17 +++++++++++++++++ src/index.js | 5 ++++- test/unique-selector.js | 21 +++++++++++++++++++++ 3 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 src/getName.js diff --git a/src/getName.js b/src/getName.js new file mode 100644 index 0000000..681ef35 --- /dev/null +++ b/src/getName.js @@ -0,0 +1,17 @@ +import 'css.escape'; + +/** + * Returns the `name` attribute of the element (if one exists) + * @param { Object } element + * @return { String } + */ +export function getName( el ) +{ + const name = el.getAttribute( 'name' ); + + if( name !== null && name !== '') + { + return `[name="${name}"]`; + } + return null; +} diff --git a/src/index.js b/src/index.js index 29cdd7c..c39ac63 100644 --- a/src/index.js +++ b/src/index.js @@ -6,6 +6,7 @@ import { getID } from './getID'; import { getClassSelectors } from './getClasses'; import { getCombinations } from './getCombinations'; import { getAttributes } from './getAttributes'; +import { getName } from './getName' import { getNthChild } from './getNthChild'; import { getTag } from './getTag'; import { isUnique } from './isUnique'; @@ -28,6 +29,7 @@ function getAllSelectors( el, selectors, attributesToIgnore ) 'attributes' : elem => getAttributes( elem, attributesToIgnore ), 'class' : getClassSelectors, 'id' : getID, + 'name' : getName, }; return selectors @@ -135,6 +137,7 @@ function getUniqueSelector( element, selectorTypes, attributesToIgnore ) { case 'data' : case 'id' : + case 'name': case 'tag': if ( testUniqueness( element, selector ) ) { @@ -173,7 +176,7 @@ function getUniqueSelector( element, selectorTypes, attributesToIgnore ) export default function unique( el, options={} ) { const { - selectorTypes=['id', 'class', 'tag', 'nth-child'], + selectorTypes=['id', 'name', 'class', 'tag', 'nth-child'], attributesToIgnore= ['id', 'class', 'length'], selectorCache, isUniqueCache diff --git a/test/unique-selector.js b/test/unique-selector.js index 45f8f24..2b6b468 100644 --- a/test/unique-selector.js +++ b/test/unique-selector.js @@ -143,4 +143,25 @@ describe( 'Unique Selector Tests', () => expect( uniqueSelector ).to.equal( '[data-foo]' ); } ); + describe('name', () => { + beforeEach(() => { + $( 'body' ).get( 0 ).innerHTML = ''; // Clear previous appends + }) + + it( 'with value', () => + { + $( 'body' ).append( '
' ); + const findNode = $( 'body' ).find( '.test3' ).get( 0 ); + const uniqueSelector = unique( findNode ); + expect( uniqueSelector ).to.equal( '[name="so"]' ); + } ); + + it( 'without value', () => + { + $( 'body' ).append( '
' ); + const findNode = $( 'body' ).find( '.test3' ).get( 0 ); + const uniqueSelector = unique( findNode ); + expect( uniqueSelector ).to.equal( '.test3' ); + } ); + }) } );