skip to Main Content

I need to see if an input is in a class or not looking by the input

I want by this html code where the input is in a class

<div class="input-container">
    <input type="text" name="realname">
</div>

the result true

And by this html code where the input is outside a class

<div class="input-container"></div>

<input type="hidden" name="id" value="1">

the result false

The input I will get with this javascript code

element.closest('form').querySelector('input[name=' + name + ']')

3

Answers


  1. I need to see if an input is in a class or not looking by the input

    I think what you meant to say this instead:

    I need to check if the immediate-parent HTML element of an <input> element has a specific CSS class-name applied to it"

    …and that’s simple enough:

    const inputEl = element.closest('form').querySelector('input[name="' + CSS.escape( name ) + '"]');
    
    const inputElIsChildOfDivWithInputContainerCssClass = inputEl.parentElement.matches('.input-container');
    
    console.log( "result: %o", inputElIsChildOfDivWithInputContainerCssClass );
    
    Login or Signup to reply.
  2. You can make a simple check with querySelector:

    if (document.querySelector('.input-container [name="realname"]')) {
      console.log('in')
    }
    else if (document.querySelector('[name="realname"]')) {
      console.log('out')
    }
    else {
      console.log('[name="realname"] does not exist')
    }
    <div class="input-container">
        <input type="text" name="realname">
    </div>
    Login or Signup to reply.
  3. If you’re using .closest then why not:

    element.closest(".input-container") !== null ? "in" : "out"
    
    document.addEventListener("click", function(event) {
      if (event.target.tagName === "INPUT") {
        console.log(event.target.closest(".input-container") !== null ? "in" : "out");
      }
    });
    <div class="input-container">
      <input type="text" placeholder="i am in">
    </div>
    <input type="text" placeholder="i am out">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search