Greg Pettit
Greg Pettit

Reputation: 10830

CSS selector for hideous table-driven markup

JSFiddle: https://jsfiddle.net/dc9wdwem/

I inherited a legacy application that some clients are still using and expecting upgrades for. One recent upgrade "broke" the existing CSS and the easiest way to resolve it is to "un-break" just one little table.

The markup is nested table upon nested table. But for the sake of stripping down to the bare essentials, here's the barest version of where to find my table.

<div id="someId">
  <table>
    <tr>
      <td>
        <table>
          <tr>
            <td>
              <table> <!-- not this table --> </table>
            </td>
            <td>
              <table> <!-- THIS ONE!! --> </table>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</div>

There are other tables and rows and cells scattered throughout, but this structure gets you there.

Using the "direct descendant" symbol is tricky because the tables are descended within rows and cells as well as other tables. So table>table>table isn't going to do it. But then if you go with a general descendent selector, you end up selecting too many things table table table will get you a whole bunch of tables. Here's the closest I got so far:

#someId>table table td:nth-child(2) table {
  background-color: red;
}

I would normally be glad to add even more > selectors; however, I believe the browsers themselves are filling in tbody elements and so forth and I don't know that I can reasonably predict that the proper structure will always be intact. The above selector is selecting more tables than the one I'm trying to isolate.

None of the nested tables have IDs or classes, and nor do I have the opportunity to add them in. The upgrade process does not upgrade the customer's markup, which they may have themselves partially customized over time.

Anybody have any CSS selector magic that will work, assuming the above markup alongside browser-filled elements like tbody?

Upvotes: 2

Views: 40

Answers (2)

Hultman
Hultman

Reputation: 96

You missed a Table in your css.

try:

div#someId > table table table td:nth-child(2) > table

https://jsfiddle.net/ba52Lwkg/

#someId > table table:first-of-type td + td > table

this should work.

https://jsfiddle.net/dc9wdwem/

Upvotes: 1

Heretic Monkey
Heretic Monkey

Reputation: 12114

This will work for the specific HTML in your fiddle:

#someId>table table:nth-of-type(1) td:nth-of-type(2) table {
  background-color: red;
}

Obviously, if the HTML changes in pretty much any way, this is probably not going to work.

Upvotes: 1

Related Questions