How to check what heading levels are used in a post

Until the CSS :has() pseudo-class is widely supported, I want to apply CSS classes to posts that depend on the heading levels used in them. For instance, if a post only has <h1> and <h2> headings, the <h2>s should have the size of what otherwise <h3> would get.

I found a quick solution:

class="{% unless page.content contains '<h3' or page.content contains '### ' %}
       {% endunless %}"

And it works. (Oddly, depending on the post/page, the page.content's markdown is already parsed, so I need to check for the presence of both <h3> and ### tags.) The only problem is that I want to use this trick on another website that has HTML code snippets as content, so my simple test wouldn’t be reliable at all there.

Isn’t there a more elegant way to do this?