Skip to content

Commit

Permalink
#1221@minor: Add support for :target-within pseudo selector.
Browse files Browse the repository at this point in the history
  • Loading branch information
René Schleusner committed Jan 24, 2024
1 parent 47aa46b commit 75d773f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
11 changes: 8 additions & 3 deletions packages/happy-dom/src/query-selector/SelectorItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export default class SelectorItem {
*/
private matchPsuedo(element: IElement): boolean {
const parent = <IElement>element[PropertySymbol.parentNode];
const targetId = element[PropertySymbol.ownerDocument].location.hash.slice(1);
const parentChildren = element[PropertySymbol.parentNode]
? (<Element>element[PropertySymbol.parentNode])[PropertySymbol.children]
: [];
Expand Down Expand Up @@ -223,11 +224,15 @@ export default class SelectorItem {
.indexOf(element);
return nthLastOfTypeIndex !== -1 && psuedo.nthFunction(nthLastOfTypeIndex + 1);
case 'target':
const hash = element[PropertySymbol.ownerDocument].location.hash;
if (!hash) {
if (!targetId) {
return false;
}
return element.isConnected && element.id === hash.slice(1);
return element.isConnected && element.id === targetId;
case 'target-within':
if (!targetId) {
return false;
}
return element.isConnected && element.children.some((child) => child.id === targetId);
}
}

Expand Down
20 changes: 20 additions & 0 deletions packages/happy-dom/test/query-selector/QuerySelector.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1134,6 +1134,26 @@ describe('QuerySelector', () => {
expect(section.querySelector('h3:target')).toBeNull();
});

it('Returns an element matching :target-within', () => {
const section = document.createElement('section');
const headline = document.createElement('h2');
headline.id = 'id';
section.appendChild(headline);
document.appendChild(section);

window.location.hash = '#id';
expect(document.querySelector('section:target-within')).toBe(section);

window.location.hash = '#something-else';
expect(document.querySelector('section:target-within')).toBeNull();

// Detached Elements should not match
window.location.hash = '#id';
headline.remove();

expect(document.querySelector('section:target-within')).toBeNull();
});

it('Returns an element by id matching "#:id:".', () => {
const div = document.createElement('div');
const div2 = document.createElement('div');
Expand Down

0 comments on commit 75d773f

Please sign in to comment.