From 45727c4e6de7f6f6f61a4ae3589d5dd271ea8803 Mon Sep 17 00:00:00 2001 From: Lars Ingebrigtsen Date: Fri, 27 Sep 2019 00:32:37 +0200 Subject: [PATCH] Add a new `dom-search' function * doc/lispref/text.texi (Document Object Model): Document it. * lisp/dom.el (dom-search): New function. --- doc/lispref/text.texi | 5 +++++ etc/NEWS | 6 ++++++ lisp/dom.el | 12 ++++++++++++ 3 files changed, 23 insertions(+) diff --git a/doc/lispref/text.texi b/doc/lispref/text.texi index d7b04d2934f..8d78a9b24ff 100644 --- a/doc/lispref/text.texi +++ b/doc/lispref/text.texi @@ -5162,6 +5162,11 @@ which is a regular expression. Return all nodes in @var{dom} that have IDs that match @var{match}, which is a regular expression. +@item dom-search @var{dom} @var{predicate} +Return all nodes in @var{dom} where @var{predicate} returns a +non-@code{nil} value. @var{predicate} is called with the node to be +tested as its parameter. + @item dom-strings @var{dom} Return all strings in @var{dom}. diff --git a/etc/NEWS b/etc/NEWS index 0a4ada3cc6c..afeb3877739 100644 --- a/etc/NEWS +++ b/etc/NEWS @@ -275,6 +275,12 @@ obsolete, and the new utility function 'xml-remove-comments' can be used to remove comments before calling the libxml functions to parse the data. ++++ +** A new DOM (the XML/HTML document structure returned by functions +such as 'libxml-parse-html-region') traversal function has been added: +'dom-search', which takes a DOM and a predicate and returns all nodes +that match. + +++ ** The Network Security Manager now allows more fine-grained control of what checks to run via the 'network-security-protocol-checks' diff --git a/lisp/dom.el b/lisp/dom.el index d8c44339985..f01da5221b8 100644 --- a/lisp/dom.el +++ b/lisp/dom.el @@ -108,6 +108,18 @@ A name is a symbol like `td'." (cons dom matches) matches))) +(defun dom-search (dom predicate) + "Return elements in DOM where PREDICATE is non-nil. +PREDICATE is called with the node as its only parameter." + (let ((matches (cl-loop for child in (dom-children dom) + for matches = (and (not (stringp child)) + (dom-search child predicate)) + when matches + append matches))) + (if (funcall predicate dom) + (cons dom matches) + matches))) + (defun dom-strings (dom) "Return elements in DOM that are strings." (cl-loop for child in (dom-children dom) -- 2.39.2