Skip to content

Instantly share code, notes, and snippets.

@tmpvar
Forked from lloyd/level3.md
Created May 26, 2011 22:05
Show Gist options
  • Save tmpvar/994196 to your computer and use it in GitHub Desktop.
Save tmpvar/994196 to your computer and use it in GitHub Desktop.

This perhaps deserves a blog post, but whatever.

The challenge: What if you wanted to determine what level my Bulgarian language skills were at? Using this sample document:

{
    "name": {
        "first": "Lloyd",
        "last": "Hilaiel"
    },
    "favoriteColor": "yellow",
    "languagesSpoken": [
        {
            "language": "Bulgarian",
            "level": "advanced"
        },
        {
            "language": "English",
            "level": "native"
        },
        {
            "language": "Spanish",
            "level": "beginner"
        }
    ],
    "seatingPreference": [
        "window",
        "aisle"
    ],
    "drinkPreference": [
        "whiskey",
        "beer",
        "wine"
    ],
    "weight": 172
}

How would you craft a CSS-like selector to extract the value of the key level contained in an object where language has a value of Bulgarian? (i.e. match the string advanced)

NOW STOP. Don't read any more of this gist. Go think about it. Do you know any CSS that should apply here?

By this time, you've already thought of your own answer. Two possible (even complimentary) routes are in my head.

The first solution is general and has precedent in jquery/sizzle. Specifically :has() and :contains() inspired by jquery. But maybe we'd rename :contains to :val.

.languagesSpoken :has(.language:val('Bulgarian')) .level

The other route could repurpose attribute selectors to say that they match children

.languagesSpoken object[language="Bulgarian"] .level

Or

.languagesSpoken[language="Bulgarian"] .level

Note that the former is potentially much more flexible because the :has() pseudo function can take complete selectors.

Note also that the latter could be a syntactic abbreviation for the former. This is in fact how things like :first-child and :last-child are implemented in the reference implementation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment