HomeThe ClassicsFarai's Codelab

This Is The Stupidest CSS You Could Ever Write

Published:

The other day, I was working on indexing my site’s outbound links where the links to a specific domain are listed in their own <details> element with it’s id set to the domain, like this <details id="www.iea.com">...</details>. I wanted people to be able to navigate directly to a specific domain and open it’s respective <details> element through the url hash, doing something like /linkstats/#www.iea.com.

The browser can navigate to hashes just fine, issue was opening the <details> element when navigated to. Sounds simple enough as all I needed to do was check if the queried id was a details element and open it if it was, like this:

window.addEventListener("load", (e) => {
    const elem = document.querySelector(`#${window.location.hash.substring(1)}`)
    if (elem && elem.tagName === "DETAILS") {
        elem.open = true
    }
})

Do you see the problem here? As a clue, querying www.iea.com will make a query selector like #www.iea.com.

See it now?

After a little frustration, I realized that the selector was querying and element with id www and classes iea and com, something like this:

<details id="www" class="iea com">
    ...
</details>

I didn’t want that so I had to make the dumbest CSS selector possible—[id=""], turning the query selector into this instead:

document.querySelector([id='${window.location.hash.substring(1)}'])

It looks incredibly goofy, but it’s not like you have a better way to do it. You could say that this should have been a data-* attribute, but that can’t be hash navigated to. I could have used a query parameter instead but that would require writing even goofier code.

As bad as that query selector is, at least it works.