PHP Script: Hide block if less than two H2

Is there a tutorial to count all HTML elements of a certain type?

It’s about writing a PHP script that counts all H2 elements within a class and then uses Bricks Conditions to hide a TOC block if there are less than two H2 headlines on the page.

The following code shows me the correct number of H2 headlines within the post content.

<?php

$post_id = get_the_ID();

$content = get_post_field('post_content', $post_id);

$num_h2_tags = preg_match_all('/<h2[^>]*>(.*?)<\/h2>/i', $content, $matches);

echo "H2 Headlines: " . $num_h2_tags;

?>

The problem is that I work with a Bricks template and there are other H2s on the page in addition to the WordPress blog content. These are not taken into account.

DIV (.post-container-body)
-H1
-Post Content (Bricks Element)
-Another H2 (div)
-Another H2 (div)

The php Script just take note to the H2 in Post Content, not the others.

(I don’t want to solve it with JS and display: none;)