Skip to content

Commit

Permalink
Merge pull request #1235 from Schleuse/task/1221-add-support-for-targ…
Browse files Browse the repository at this point in the history
…et-and-target-within

#1221@minor:  Add support for `:target` pseudo selector.
  • Loading branch information
capricorn86 committed Feb 26, 2024
2 parents 4ef032f + f53a847 commit efb48f0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/happy-dom/src/query-selector/SelectorItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,12 @@ export default class SelectorItem {
.reverse()
.indexOf(element);
return nthLastOfTypeIndex !== -1 && psuedo.nthFunction(nthLastOfTypeIndex + 1);
case 'target':
const hash = element[PropertySymbol.ownerDocument].location.hash;
if (!hash) {
return false;
}
return element.isConnected && element.id === hash.slice(1);
}
}

Expand Down
25 changes: 25 additions & 0 deletions packages/happy-dom/test/query-selector/QuerySelector.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1115,6 +1115,31 @@ describe('QuerySelector', () => {
expect(div.querySelector('#id') === div2).toBe(true);
});

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

window.location.hash = '#id';
expect(section.querySelector(':target')).toBe(headline);
expect(section.querySelector('h2:target')).toBe(headline);
expect(section.querySelector('h3:target')).toBeNull();

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

// Detached Elements should not match
window.location.hash = '#id';
section.remove();
expect(section.querySelector(':target')).toBeNull();
expect(section.querySelector('h2:target')).toBeNull();
expect(section.querySelector('h3:target')).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 efb48f0

Please sign in to comment.