DEV Community

Adam Crockett
Adam Crockett

Posted on

Query the DOM using ES6

🤔 Why do you need to include the language version? such simple task, you must be thinking.

Yes you,

I'm talking to you, the one with the haircut that's this long:
who me?

...wait we all have hair like this don't we?

Well believe it or not I'm about to teach you something so blindingly obvious, you'll kick yourself that you didn't spot it, call your relatives and tell them before forgetting about this again.

Let's query

Why do this?

const username = document.getElementById("#username");
const password = document.getElementById("#password");
Enter fullscreen mode Exit fullscreen mode

when you can do this ES6 de-structure that NodeList

const [username, password] = document.querySelectorAll("#username, #password");
Enter fullscreen mode Exit fullscreen mode

One call to query the DOM, but this only works for finite queries which can be determined, you know you have 2 IDs and so should not have any other elements returned, or perhaps you query on some other attribute, as long as the results are predictable this will work nicely.

When are results predictable, forms should be at least?

I submit that this isn't for everything 💜

Top comments (0)