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

fix: [1710] - Ensure querySelector returns the first item that appears in the DOM for grouped selectors #1713

Merged

Conversation

christiango
Copy link
Contributor

Fixes #1710

Added a test case to query selector that in the current build of happy-dom fails due to it returning the first item that matches the grouped selector instead of the first element in the DOM that matches any selector in the group. This matches the behavior of Chromium browsers as well as JSDOM.

selector: string,
cachedItem: ICachedQuerySelectorAllItem | ICachedQuerySelectorItem
): void {
const groups = SelectorParser.getSelectorGroups(selector);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

My main concerns with this change are the following:

  • I'm new to this project so I'm afraid this may have some unexpected consequences due to the complex nature of the caches required to make these perform well
  • I'm not sure how much this impacts performance of the library all up, particularly in less complicated query selector scenarios than the one described in the bug.

Copy link
Owner

@capricorn86 capricorn86 left a comment

Choose a reason for hiding this comment

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

Thank you for contributing @christiango! ⭐

I believe that this fix would have a big impact on performance.

I think the best way to solve this bug is to add support for returning DocumentPositionAndElement to findFirst() (similar as what findAll() does). Then querySelector() collects the matches for all groups and sorts them by position (similar to what querySelectorAll() does).

@christiango
Copy link
Contributor Author

Great suggestion, I'll give that a shot!

Copy link
Owner

@capricorn86 capricorn86 left a comment

Choose a reason for hiding this comment

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

Nice work! 🙂

@capricorn86 capricorn86 merged commit 5551267 into capricorn86:master Feb 8, 2025
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

QuerySelector returning incorrect results when using a grouped selector
2 participants