Skip to content

Instantly share code, notes, and snippets.

@bloodyowl
Created November 11, 2012 01:02
Show Gist options
  • Save bloodyowl/4053214 to your computer and use it in GitHub Desktop.
Save bloodyowl/4053214 to your computer and use it in GitHub Desktop.
Craft.js Simple CSS-like selector

Simple CSS-Like selectors for Craft.js

Usage

Different queries separated by a comma. Only use #id, .class, tag (no pseudo selectors).

$$("#id .class tag, tag, #id tag")

output (Array) A list of elements

/*
Craft.js Simple CSS-like selector
handles ids, classnames and tagnames (no advanced selector here)
357B minified
*/
function $$(string){
var cleanSelector = /[\.#]/
, selectors = string.split(/\s?,\s?/)
, result = []
, getters = ["getByClass","getByTag"]
function getEls(selector, context){
var charAt = selector.charAt(0)
, toSelect = charAt == "#" ? 3 : charAt == "." ? 0 : 1
, cleanedSelector = selector.replace(cleanSelector, "")
, isFound
if(toSelect == 3) return (isFound = $(cleanedSelector)).id ? isFound : []
if(!context) return Element[getters[toSelect]](cleanedSelector)
if(Object.typeOf(context) != "array") return context[getters[toSelect]](cleanedSelector)
return context.invoke(getters[toSelect], cleanedSelector).group()
}
selectors.forEach(function(selector){
var hierarchy = selector.split(/\s/)
, cache
hierarchy.forEach(function(item){
cache = getEls(item, cache)
})
result = result.concat(cache)
})
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment