Search code examples
javascripthtmlcsscss-selectors

Applying a class to parents of a specific class


I have a bunch of tables in an HTML document. Some of the cells have a certain class of span inside them (.signs); some of them don't. And I need to apply a border specifically to the ones containing .signs. (The purpose of this is to show how big the row and column spans are, so I can't just put the border on the .signs itself.)

I know that CSS selectors can't check the children of an element, only its parents. So instead, I'd like to write a JavaScript function that finds every td containing a .signs, and tags it with a special class. The CSS can then attach to that class.

What's the best way to do this? It seems like a task that should have a simple and obvious solution. My first thought is to use document.getElementsByTagName to iterate over all tds, then use element.getElementsByClassName to see if there's a .signs inside it, but there might be some elegant trick with selectors that won't require so much iteration.

(I'm not currently using JQuery in this project, and would prefer not to add such a heavy dependency just for this one task.)


Solution

  • https://developer.mozilla.org/en-US/docs/Web/CSS/:has

    You can use :has selector to find cells containing the span.

    You can also find the spans and use closest('td') to find their parent cells.

    document.querySelectorAll('table .signs').forEach(span => span.closest('td').style.backgroundColor = 'yellow');
    td:has(span.signs){
      border: 1px solid gray;
    }
    <table>
    <tr><td><span class="signs">signs</td><td>cell</td></tr>
    </table>