-1

I'm trying to search an array of HTML elements with search value from another array. Inside a function getElement() there is an array order which holds string value. This array determines the order of search. Also there is another array elements with all the html elements to be searched. The function block looks like

getElement(){
    const order = ['email-error', 'name-error', 'age-error'];
    const elements = document.querySelectorAll('[data-status]')
    
}

When there is a validation error, html elements will be attached with data-status property. In case of a validation error, the getElement() function is called. The value of the data-status will be email-error for email input, name-error for name input etc.

What I'm trying to achieve is; for eg: take a value from order array, say email-error. Search the elements array if it has an element with data-status="email-error". If it exists, return the element and stops the search; else search with all values from order array.

simpywatch
  • 43
  • 5
  • Do you have to define the `elements` variable? Because you could call `querySelectorAll('[data-status="email-error"]')` and so on. – Passerby Aug 11 '21 at 14:17

3 Answers3

1

I've written some HTML to test the code.

This is is the way to do it, if you want to loop over all array values and check:

function getElement() {
        const order = ['email-error', 'name-error', 'age-error'];
        const elements = document.querySelectorAll('[data-status]')
        let foundElement = null

        elements.forEach((elem) => {
            if (order.includes(elem.getAttribute('data-status')) && !foundElement) {
                foundElement = elem
            }
        })
        return foundElement
    }
    console.log(getElement())
<div data-status="email-error"></div>
<div data-status="name-error"></div>
<div data-status="test-class"></div>
Amirhossein Shahbazi
  • 1,082
  • 1
  • 6
  • 13
-1

Maybe you could do a function on your own like this: https://stackoverflow.com/a/784015/13604954

Or use the built-in Array.prototype.includes:

https://stackoverflow.com/a/40717204/13604954

Patfreeze
  • 680
  • 6
  • 16
-2

You could implement a nested loop.

for(let i = 0; i < order.length; i++) {
  for(let j = 0; j < elements.length; j++) {
    if( order[i] == elements[j] ) {
      return orders[i] 
    }
  }
}

This will loop through both arrays fully, matching each value from one array to each value from the other unless there's a match, in which case it would return the matching element and break the loop.

You could also use the built in JS .forEach() method, which automatically loops through arrays.

order.forEach(orderEl => {
    elements.forEach(elementEl => {
        if (orderEl === elementEl) {
             return orderEl
        }
    })
})
RA M
  • 38
  • 4