What is the opposite of :has() in jQuery to target the parent table having nested table

Viewed 183

I have a nested table as below -

<table class="table parent">
<tbody>
    <tr>
    <td>TEXTA</td>
    <td>TEXTB</td>
    </tr>
    <tr>
    <td>Has nested table below
        <table class="table nested">
        <tbody>
        <thead>
        <th>S.No.</th>
        <th>Name</th>
        <th>Contact</th>
        </thead>
        <tr>
        <td>1</td>
        <td>ABC</td>
        <td>PQR</td>
     </tr>
     </tbody>
     </table>
     </td>
     </tr>
   <tr>
    <td>TEXTC</td>
    <td>TEXTD</td>
    </tr>
</tbody>
</table>

If I want to add a background only to the td of nested table I could write something like -

$( "td" ).has( "table" ).css( "background-color", "red" ); 

but I want to select only parent td or td that does not have a nested table, how can I achieve this?

I am basically trying to change the width of ONLY those td that do NOT contain the nested table. So, in this case the width of only td containing TEXTA and TEXTC should change.

If there is a way to achieve this through CSS alone, please let me know.

Thanks in advance !!

2 Answers

You can target the parent td's excluding the nested table using Descendant Selector along with .not(':has("table")')

$(".parent > tbody > tr > td").not(':has("table")').css("background-color", "red");

Live Demo:

$(".parent> tbody > tr > td").not(':has("table")').css("background-color", "red");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table parent">
  <tbody>
    <tr>
      <td>TEXTA</td>
      <td>TEXTB</td>
    </tr>
    <tr>
      <td>Has nested table below
        <table class="table nested">
          <tbody>
            <thead>
              <th>S.No.</th>
              <th>Name</th>
              <th>Contact</th>
            </thead>
            <tr>
              <td>1</td>
              <td>ABC</td>
              <td>PQR</td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
    <tr>
      <td>TEXTC</td>
      <td>TEXTD</td>
    </tr>
  </tbody>
</table>

Just invert it via .not(), feeding your :has pseudo selector to it.

$("td").not(':has("table")').css( "background-color", "red" ); 

Or even

$("td:not(:has(table))").css( "background-color", "red" ); 
Related