Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deleting elements with selectors? #41

Open
vspinu opened this issue Sep 27, 2016 · 5 comments
Open

Deleting elements with selectors? #41

vspinu opened this issue Sep 27, 2016 · 5 comments
Labels
category: ergonomics Quality of Life improvements type: feature request Feature requests

Comments

@vspinu
Copy link

vspinu commented Sep 27, 2016

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.

@davidsantiago
Copy link
Collaborator

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.

@vspinu
Copy link
Author

vspinu commented Sep 28, 2016

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
Copy link
Author

vspinu commented Oct 7, 2016

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.

@eigenhombre
Copy link

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!

@ghost
Copy link

ghost commented Apr 24, 2018

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)))))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
category: ergonomics Quality of Life improvements type: feature request Feature requests
Projects
None yet
Development

No branches or pull requests

4 participants