(ns dom.core (:require [clojure.string :as str] [clojure.set :refer [difference union]])) ; sample usage: ; (-> (all ".class") (hide) (+css "titi") (clear) (html "zob") (show)) (defn- nodelist-coll [nodelist] (doall (map #(.item nodelist %) (range (.-length nodelist))))) (defn- coll! [item] (cond (coll? item) item (nil? item) [] [item])) (defn +css "add classname(s) to given nodes" [nodes css] (let [cnodes (coll! nodes) +cn (set (str/split css #"\s+"))] (doseq [n cnodes] (let [c (union (set (str/split (.-className n) #"\s+")) +cn)] (set! (.-className n) (str/join " " c)))) nodes)) (defn -css "remove classname(s) of given nodes" [nodes css] (let [cnodes (coll! nodes) -cn (set (str/split css #"\s+"))] (doseq [n cnodes] (let [c (difference (set (str/split (.-className n) #"\s+")) -cn)] (set! (.-className n) (str/join " " c)))) nodes)) (defn hide "hide the given nodes" [nodes] (doseq [n (coll! nodes)] (set! (.-display (.-style n)) "none")) nodes) (defn show "display the given nodes" [nodes] (doseq [n (coll! nodes)] (set! (.-display (.-style n)) "block")) nodes) (defn html ([nodes html] "setup inner html of given nodes" (doseq [n (coll! nodes)] (set! (.-innerHTML n) (or html ""))) nodes) ([html] "create html element from an html string, returning generated nodes" (let [div (.createElement js/document "div")] (set! (.-innerHTML div) (or html "")) (nodelist-coll (.childNodes div))))) (defn clear "remove children of given nodes" [nodes] (html nodes "")) (defn all "return an HTMLElement collection matching the given selector" [selector] (let [nodelist (.querySelectorAll js/document selector)] (nodelist-coll nodelist))) (defn one "return the first HTMLElement matching the given selector" [selector] (first (all selector))) (defn append-to "append nodes to the first match of given selector" [nodes selector] (let [dst-node (one selector)] (if (not (nil? dst-node)) (doseq [n (coll! nodes)] (.appendChild dst-node n))) nodes))