Skip to content

feat: considerations for elements within ShadowRoot #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ This is particularly useful when tracking in custom variables in analytics:
_gaq.push(['_trackEvent', 'Engagement', 'Click', selector]);
}, false);

Selector uniqueness is determined based on the given element's root node. Elements rendered within Shadow DOM will derive a selector unique within the associated ShadowRoot context. Otherwise, a selector unique within an element's owning document will be derived.

Installation
------------
Expand Down Expand Up @@ -74,6 +75,11 @@ Eric Clemmons : [@ericclemmons](https://twitter.com/ericclemmons)

Releases
--------

- v2.1.0

-

- v0.1.0

- Big refactor/rewrite using es6
Expand Down
11 changes: 8 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,9 @@ function getUniqueSelector( element, selectorTypes, attributesToIgnore, filter )
}

/**
* Generate unique CSS selector for given DOM element
* Generate unique CSS selector for given DOM element. Selector uniqueness is determined based on the given element's root node.
* Elements rendered within Shadow DOM will derive a selector that is unique within the associated ShadowRoot context.
* Otherwise, a selector that is unique within the element's owning document will be derived.
*
* @param {Element} el
* @param {Object} options (optional) Customize various behaviors of selector generation
Expand All @@ -200,7 +202,6 @@ function getUniqueSelector( element, selectorTypes, attributesToIgnore, filter )
* @return {String}
* @api private
*/

export default function unique( el, options={} ) {
const {
selectorTypes=['id', 'name', 'class', 'tag', 'nth-child'],
Expand Down Expand Up @@ -248,7 +249,11 @@ export default function unique( el, options={} ) {
if (isUniqueSelector) {
return maybeUniqueSelector
}
currentElement = currentElement.parentNode

// Using parentElement here (rather than parentNode) to
// filter out any document/document fragment nodes that may
// be ancestors to elements within Shadow DOM trees.
currentElement = currentElement.parentElement
}

return null;
Expand Down
13 changes: 10 additions & 3 deletions src/isUnique.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
/**
* Checks if the selector is unique
* Checks if the selector is unique. The selector is unique
* if the elements root node (either its owner document, or a shadow root)
* has exactly one element matching the selector.
*
* @param { Object } element
* @param { String } selector
* @return { Array }
* @return { Boolean }
*/
export function isUnique( el, selector )
{
if( !Boolean( selector ) ) return false;
try {
var elems = el.ownerDocument.querySelectorAll(selector);
// Using getRootNode here to scope checks to any parent
// ShadowRoot. getRootNode will otherwise return the
// document associated to the elements page/frame (like
// the ownerDocument property would).
var elems = el.getRootNode().querySelectorAll(selector);
Comment on lines +14 to +18

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TIL 🧠

return elems.length === 1 && elems[0] === el;
} catch (e) {
return false
Expand Down
46 changes: 46 additions & 0 deletions test/unique-selector.js
Original file line number Diff line number Diff line change
Expand Up @@ -299,4 +299,50 @@ describe( 'Unique Selector Tests', () =>
expect( uniqueSelector ).to.equal( 'span' );
})
})

describe('shadow dom', () => {
it( 'builds expected selector inside and outside shadow context', () => {
$( 'body' ).append( '<div id="shadow-host" class="shadow-host-class"></div>' );

const hostNode = $( '#shadow-host' ).get( 0 );

const shadowRoot = hostNode.attachShadow({ mode: "open" })
const shadowElement = hostNode.ownerDocument.createElement('div')
shadowElement.innerHTML = `
<div id="inner-shadow-container">
<button id="shadow-button" class="shadow-button-class">Click Me</button>
</div>
`
shadowRoot.appendChild(shadowElement);

const uniqueSelectorForHost = unique( hostNode );
expect( uniqueSelectorForHost ).to.equal( '#shadow-host' );

const uniqueSelectorForShadowContent = unique ( shadowElement.querySelector('#shadow-button') )
expect( uniqueSelectorForShadowContent ).to.equal( '#shadow-button' );
})

it( 'builds unique selector scoped to shadow root', () => {
$( 'body' ).append( '<div id="shadow-host" class="shadow-host-class"></div>' );
$( 'body' ).append( '<button class="shadow-button-class">Click Me Third</button>' );

const hostNode = $( '#shadow-host' ).get( 0 );

const shadowRoot = hostNode.attachShadow({ mode: "open" })
const shadowElement = hostNode.ownerDocument.createElement('div')
shadowElement.innerHTML = `
<div id="inner-shadow-container">
<button class="shadow-button-class">Click Me First</button>
<button class="shadow-button-class">Click Me Second</button>
</div>
`
shadowRoot.appendChild(shadowElement);

const uniqueSelectorInRootDocument = unique( $( 'body' ).find( '.shadow-button-class' ).get( 0 ) );
expect( uniqueSelectorInRootDocument ).to.equal( '.shadow-button-class' );

const uniqueSelectorForShadowContent = unique ( shadowElement.querySelectorAll('.shadow-button-class')[0] )
expect( uniqueSelectorForShadowContent ).to.equal( '#inner-shadow-container > :nth-child(1)' );
})
})
} );