-
-
Save danieldroit/4acf6f71126f8f8fc7ba11378d643651 to your computer and use it in GitHub Desktop.
minimalist dom manipulation clojure script library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns dom.core | |
(:require [clojure.string :as str] | |
[clojure.set :refer [difference union]])) | |
; sample usage: | |
; (-> (all ".class") (hide) (+css "titi") (clear) (html "<span>zob</span>") (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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment