javascripthtmlcssqueryselector

css selector issue with valid and nested invalid


I am currently trying to figure out the following situation.

const invalidInput = document.querySelector('.ng-invalid:not(.no-check, .ng-invalid *)');

console.log(invalidInput.name);
<div class="ng-valid no-check">
  <div class="ng-invalid">
    <span>(</span>
    <input class="ng-invalid" name="hello" id="hello">
    <span>)</span>
    <input class="ng-invalid" name="hello2" id="hello2">
  </div>
</div>
<br>
<input class="ng-invalid" name="hello3" id="hello3">

the output should log hello3

here is the fiddle : fiddle


Solution

  • Assuming that your input is inside a div container, you can get your un-nested element by using direct child selector >:

    const invalidInput = document.querySelector('.container > .ng-invalid:not(.no-check)');
    
    console.log(invalidInput.name);
    <div class="container">
      <div class="ng-valid no-check">
        <div class="ng-invalid">
          <span>(</span>
          <input class="ng-invalid" name="hello" id="hello">
          <span>)</span>
          <input class="ng-invalid" name="hello2" id="hello2">
        </div>
      </div>
      <br>
      <input class="ng-invalid" name="hello3" id="hello3">
    </div>