1
<div>
    <!-- h1 with a span -->
    <h1> 
        <span>...</span> 
    </h1>
    <table>
        ...

    <!-- h1 without a span -->
    <h1>...</h1>
    <table>
        ...

How I can select the table that comes immediately after the <h1> that surrounds a <span>? I tried h1 span + table so that table is using the adjacent operator. However, it doesn't work. It's probably because table is being shown as adjacent to the <span> and not the <h1>. Any hints?

Grateful
  • 7,657
  • 7
  • 34
  • 59

3 Answers3

1

As you are open to JavaScript solution, here's what I've done.

var elms = document.getElementsByTagName('h1');

for(var i = 0; i < elms.length; i++) {
  var elm = elms[i];
  
  if(!(elm.getElementsByTagName('span').length > 0))
    elm.className = "select-next-table";
}
.select-next-table + table {
  border: 1px solid red;
}

table {
  width: 100px;
  height: 100px;
  border: 1px solid #000;
}
<h1><span>Don't select the next table</span></h1>
<table></table>

<h1>Select the next table</h1>
<table></table>

What am doing here is fetching all h1 tags and looping them. Later, I try to search span inside the h1 tag, if I don't get any, then I append a class to the h1 element, and later, I use .select-next-table + table to select the tables which are adjacent to h1 tags, and the h1 doesn't have any span tags.


You can definitely select the table which is rendered after h1 using

h1 + table

But you cannot check whether the h1 contains a span element because once you go inside the h1 tag, you cannot select the parent again. Hence, for such things, you might have to use JavaScript.

Mr. Alien
  • 140,764
  • 31
  • 277
  • 265
0

Your code is checking for a table which is the first sibling after a span element inside an h1. I don't think you can select a table based on the span.

But you can add a class to the h1 and do h1.class + table Or maybe use the nth-child selector h1:nth-child(1) + table.

Rob Monhemius
  • 3,956
  • 2
  • 10
  • 29
0

The h1 span + table selects a table that is placed immediately after <span> within <h1> element. But you want to select a table that is placed after <h1>, thus you need to use h1 + table selector. The :has() pseudo-class could help you to apply the rule only if <h1> contains a <span> tag:

h1:has(span) + table

The trouble is the Selectors Level 4 is still not supported by any browser. But it makes possible to set special class attribute value for specified tables via jQuery.

$("h1:has(span)+table").addClass("special");
.special {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
  <span>H1 with &lt;span&gt;</span>
</h1>
<table>
  <tr><td>special style</td></tr>
</table>
<h1>H1 without &lt;span&gt;</h1>
<table>
  <tr><td>common style</td></tr>
</table>
Alexander
  • 3,922
  • 7
  • 24
  • 34