Skip to content

:target doesn't match elements on initial page load in Chrome and Firefox #2679

@zzzzBov

Description

@zzzzBov

I'm able to reproduce this issue in Firefox 41.0.2 and Chrome 46.0.2490.80 m

Basically, selecting $(':target') during initial page load to a url that contains a document fragment fails to select the targeted element.

<!DOCTYPE html>
<html>
<head>
    <title>:target Bug</title>
    <style>
        :target {
            background-color: red;
        }
    </style>
</head>
<body>
    <a href="#test" id="test">Test</a>
    <script src="http://code.jquery.com/jquery-2.1.4.js"></script>
    <script>
        $(':target').css('color', 'yellow');
        $(location.hash).css('border', '10px solid green');
        console.log('initial page request', document.querySelector(':target'));
        document.body.onload = function () {
            console.log('page load', document.querySelector(':target'));
        }
    </script>
</body>
</html>

This is caused by document.querySelectorAll(':target') returning null before page load (and sometimes it returns null after page load). Sizzle pipes the selector through querySelectorAll, which produces incorrect results.

I've created a codepen that shows this behavior. Please view it in debug mode with the document fragment.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions