Search code examples
javascriptjqueryselectors-api

Select elements contain no specified son node with pure js


$("td:not(:has(input))").each(function ( index,element){
console.log(index);
console.log(element);
console.log($(this).text())});
td {
  border: 1px solid black;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>test1</td>
    <td>test2</td>
  </tr>
  <tr>
    <td><input type="text">test3</td>
    <td><input type="text">test4</td>
  </tr>
</table>

I want to select all td which contain no son node input,that is to say,what i expect is as below:

<td>test1</td>
<td>test2</td>

It's verified by jquery's select expression td:not(:has(input)) ,it works fine.
There is a famous webpage You Don't Need jQuery! and a book Beyond jQuery.

You Don't Need jQuery!

Let's try with pure javascript.

Can we fulfill the work with pure js?


Solution

  • There's no :has selector alternative in native JS, you could do this by looping through all the td's and check manually:

    document.querySelectorAll("td").forEach(function(element) {
      if (!element.querySelector('input')) {
        console.log(element.innerText);
      }
    });
    td {
      border: 1px solid black;
    }
    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table>
      <tr>
        <td>test1</td>
        <td>test2</td>
      </tr>
      <tr>
        <td><input type="text">test3</td>
        <td><input type="text">test4</td>
      </tr>
    </table>