Level of a node based on capture group?

Hello,

for the past few days I have been working on a fork to the nvim-ts-rainbow plugin: nvim-ts-rainbow2. I am pretty much done, except for one small issue: finding out the level of a node relative to other container nodes. I know how to determine the level of a node in the tree (just keep counting up from 1 while going through the parents until I hit the root), but that is not what I need.

Consider this HTML code as an example:

<a href="https://example.com">
    Example<br/>link
</a>

The entire block is a node of type element and I want to highlight the opening and closing tags. The query is

(element
   ((start_tag) @opening
    (end_tag) @closing)) @container

Note the @container capture group. I want to know the level of the @container node relative to other @container nodes. So what I need is a way to count upwards through the tree while skipping any node which has not matched @container. HTML is simple because there is only one query for the entire language, but other languages are more complicated. For example, in C I might have a parenthesized expression inside an if-block, inside a for-loop inside a function definition. All of these will be matched by different queries, but each query will have an outer-most @container capture. Here are all the queries I have so far for C:

(parameter_list
   (("(" @opening)
    (")" @closing))) @container

(argument_list
   (("(" @opening)
    (")" @closing))) @container

(parenthesized_expression
  (("(" @opening)
   (")" @closing))) @container

(compound_statement
  (("{" @opening)
   ("}" @closing))) @container

(initializer_list
  (("{" @opening)
   ("}" @closing))) @container

(subscript_expression
  (("[" @opening)
   ("]" @closing))) @container

(field_declaration_list
   (("{" @opening)
    ("}" @closing))) @container

Is there a way to do this? I need to know the level so I can apply the correct highlight group. Otherwise the colours will look like they are totally arbitrary.