Skip to content
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

#1221@minor: Add support for :target pseudo selector. #1235

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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