Search code examples
javascriptarraysecmascript-6nodelist

Es6 how to check if an item exists in an array built from a nodeList using includes()


I cant seem to figure this one out I am trying to check if an input is inlcuded in an array of nodes. No matter what I try it seems to return false. I'm thinking it must be something simple that I'm missing.

Here is what I have

const error = document.getElementsByClassName('has-form-error')
let focusedInputNodeList = error[0].childNodes
let focusedInput = Array.from(focusedInputNodeList)

This is to check for the most immediate form error. I then want to check the return if it is an input, textarea, or select.

the above code returns the array to console from my html

(6) [text, label, text, div.form-error, input#first_name, text]

Then I try

console.log(focusedInput.includes('input')) //returns false

I figured maybe it was due to the #first_name so I tried using

console.log(focusedInput.includes('text')) //returns false

and

console.log(focusedInput.includes('#text')) //returns false

None of these attempts seemed to work. My goal is to eventually have something that looks like

if (focusedInput.includes('input')) {
    focusedInput[4].focus() //even better if I could find a way to select focusedInput.input.focus()  
}
if (focusedInput.includes('textarea')) {
    focusedInput[5].focus() // even better if I could find a way to select focusedInput.textarea.focus()
}

Solution

  • The problem is that your array focusedInput contains elements and not strings. In the code below I get an additional array of the element types, as strings, and from that you can find what you want.

    The other thing I did was to use .children to get all of the non-text elements to reduce what is in the array.

    const error = document.querySelector('.has-form-error');
    let focusedInputNodeList = error.children;
    let focusedInput = Array.from(focusedInputNodeList);
    let nodeTypes = focusedInput.map(el=>el.localName);
    console.log(focusedInput);
    console.log(nodeTypes.indexOf('label'));
    console.log(nodeTypes.indexOf('input'));
    <div class="has-form-error">
      <label>Click me</label>
      <div class="form-error">Error</div><input id="first_name" />
    </div>

    UPDATE

    In a comment you said: "even better if I could find a way to select focusedInput.input.focus()"

    So why not do this:

    const input = document.querySelector('.has-form-error input');
    if (input) {
      input.focus();
    }
    <div class="has-form-error">
      <label>Click me</label>
      <div class="form-error">Error</div><input id="first_name" />
    </div>