hickory icon indicating copy to clipboard operation
hickory copied to clipboard

Deleting elements with selectors?

Open vspinu opened this issue 7 years ago • 5 comments

Would be nice to be able to modify trees with selectors. Something like

(hs/remove selector-fn hickory-tree)

This is more general than #28.

vspinu avatar Sep 27 '16 16:09 vspinu

Hickory lets you make any modification you want to the tree using Clojure's Zipper interface, just use select-locs or select-next-loc instead of select, and you'll be returned a Clojure zipper that you can do modifications on.

davidsantiago avatar Sep 27 '16 19:09 davidsantiago

and you'll be returned a Clojure zipper that you can do modifications on.

Thanks. I will try it out and will post an example here for the reference.

vspinu avatar Sep 28 '16 09:09 vspinu

I finally got down to figuring this out:

(defn hickory-remove [selector-fn hickory-tree]
  (loop [zip (hickory.zip/hickory-zip hickory-tree)
         next (hs/select-next-loc selector-fn zip)]
    (if next
      (let [new-zip (zip/remove next)]
        (recur new-zip (hs/select-next-loc selector-fn new-zip)))
      (zip/root zip))))

Usage:

(hickory-remove (hs/node-type :comment) tt)

I think it's a useful utility, but feel free to close if you think it's not worth including into the package.

vspinu avatar Oct 07 '16 12:10 vspinu

An actual example in the docs (such as this one, or even simpler) of combining selectors and zippers to modify some HTML would be helpful!

eigenhombre avatar Aug 28 '17 16:08 eigenhombre

here an even more generic function:

(defn hickory-update [selector-fn hickory-tree zip-fn]
  (loop [zip (hickory.zip/hickory-zip hickory-tree)
         next (hickory.select/select-next-loc selector-fn zip)]
    (if next
      (let [new-zip (zip-fn next)]
        (recur new-zip (hickory.select/select-next-loc selector-fn new-zip)))
      (zip/root zip))))

; example: replace h3 by h2 tag
(defn replace-h3-h2 [t]
  (hickory-update
   (hickory.select/tag :h3)
   t
   #(zip/edit
     %
     (fn [n]
       (assoc n :tag :h2)))))

ghost avatar Apr 24 '18 11:04 ghost