Skip to content

Instantly share code, notes, and snippets.

Last active Dec 14, 2015
What would you like to do?
Basic CSS3 Selector to Clojure Enlive vector format converter
;[org.jodd/jodd-lagarto "3.4.2"]
;(:import [jodd.csselly CSSelly CssSelector Combinator Selector$Type])
(defn format-attr-selector [x]
(case (.getName x)
"id" (str "#" (.getValue x))
"class" (str "." (.getValue x))
(defn format-selector [x]
(condp #(= %1 (.getType %2)) x
Selector$Type/ATTRIBUTE (format-attr-selector x)
Selector$Type/PSEUDO_CLASS ""
Selector$Type/PSEUDO_FUNCTION ""
(defn parse-selector [x]
(let [count (.selectorsCount x)
combinator (.getCombinator x)
useCombinator (and (not (nil? combinator)) (not= combinator Combinator/DESCENDANT))
sel (keyword (apply str
(conj (map #(format-selector (.getSelector x %)) (range 0 count))
(.getElement x))))]
(if useCombinator
[sel (keyword (.getSign combinator))]
(defn parse-css [x]
(let [sel (.parse (CSSelly. x))]
(vec (flatten (map parse-selector sel)))))
(parse-css "body > *") ; => [:body :> :*]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment