Shinmera / plump

Practically Lenient and Unimpressive Markup Parser for Common Lisp
https://shinmera.github.io/plump
zlib License
119 stars 21 forks source link

add `get-element-by-class`? #31

Closed parjanya closed 3 years ago

parjanya commented 3 years ago

Hi!

I’ve been using this function, slightly massaged out from the existing code. Perhaps it could be useful to add it to the package:

(defun get-element-by-class (node class)
  "Accepts the DOM root element (a PLUMP-DOM:ROOT object) containing the DOM representation of the page which contains the list of elements.
Returns a DOM:ELEMENT holding the table with the list of elements."
  (labels ((scanren (node)
             (loop for child across (plump:children node)
                   do (when (plump:element-p child)
                        (let ((cid (plump:attribute child "class")))
                          (when (string-equal class cid)
                            (return-from get-element-by-class child)))
                        (scanren child)))))
    (scanren node))
  NIL)
Shinmera commented 3 years ago

This does not deal with nodes properly that contain multiple classes, and only ever returns the first occurrence of the class. Typically for such a situation you would use the id instead of a class, as classes are expected to be combined and used multiple times throughout the document.

In general for tree search operations like this it's better to rely on the CLSS library instead, which is linked in the readme.