Emacs: Select Current HTML Element

By Xah Lee. Date: . Last updated: .
(defun xah-html-select-element (&optional zinteract-p)
  "Select previous element before cursor.
Repeated call will extend selection to previous element, possibly parent.
After this command is called, press `xah-repeat-key' to repeat it.

In lisp code, return a vector of begin end positions.
zinteract-p if true means setup key to repeat, variable `xah-repeat-key'.

URL `http://xahlee.info/emacs/emacs/emacs_html_select_current_element.html'
Created: 2021-06-19
Version: 2025-08-09"
  (interactive (list t))
  (when zinteract-p (set-transient-map (let ((xkmap (make-sparse-keymap))) (define-key xkmap (kbd (if (boundp 'xah-repeat-key) xah-repeat-key "RET")) #'xah-html-select-element) xkmap)))
  (let (xbeg xend xtagPos1 xnewbeg xnewend)
    (if (and (eq 'xah-html-select-element last-command) (region-active-p))
        (progn
          (setq xbeg (region-beginning) xend (region-end))
          (goto-char xbeg)
          (setq xtagPos1 (re-search-backward "<[a-z0-9]+\\|</[a-z0-9]+" nil t))
          (if (xah-html--tag-self-closing-p (xah-html--get-tag-name xtagPos1))
              (progn
                (setq xnewbeg xtagPos1)
                (setq xnewend xend))
            (progn
              (if (xah-html--opening-tag-p xtagPos1)
                  (progn
                    (goto-char (1+ xtagPos1))
                    (xah-html-skip-tag-forward)
                    (search-backward "<" nil t)
                    (search-forward ">" nil t)
                    (setq xnewend (point))
                    (setq xnewbeg xtagPos1))
                (progn
                  (goto-char (1+ xtagPos1))
                  (xah-html-skip-tag-backward)
                  (setq xnewbeg (point))
                  (setq xnewend xend))))))
      (progn
        (skip-chars-forward "^<>")
        (setq xbeg (re-search-backward "<[a-z0-9]+\\|</[a-z0-9]+"))
        (setq xend (search-forward ">"))
        (if (xah-html--tag-self-closing-p (xah-html--get-tag-name xbeg))
            (progn
              (setq xnewbeg xbeg)
              (setq xnewend xend))
          (if (xah-html--opening-tag-p xbeg)
              (progn
                (goto-char (1+ xbeg))
                (xah-html-skip-tag-forward)
                (setq xnewend (point))
                (setq xnewbeg xbeg))
            (progn
              (goto-char (1+ xbeg))
              (xah-html-skip-tag-backward)
              (setq xnewbeg (point))
              (setq xnewend xend))))))
    (progn
      (push-mark xnewend t t)
      (goto-char xnewbeg))
    (vector xnewbeg xnewend)))

you need some commands in Emacs: Xah HTML Mode 📦

Xah Talk Show 2021-06-22 emacs lisp live coding, extend xah-html-select-current-element