DEV Community

loading...
Cover image for The 3 most common DOM selectors

The 3 most common DOM selectors

Aya Bouchiha
Full stack web developer
Updated on ・1 min read

Hello, on this amazing day, we'll discuss the 3 most common Javascript selectors.

getElementById

getElementById is used to return an element using his id. If there is no element with the giving id, it returns null.

<h1 id="logo">Aya Bouchiha</h1>
<script>
    const logo = document.getElememntById('logo');
    const img  = document.getElementById('img'); // null
</script>
Enter fullscreen mode Exit fullscreen mode

querySelector

querySelector is used to return the first element that matches the giving CSS selector.

<input type="search" placeholder="search" />
<script>
const searchInput = document.querySelector("[type='search']");
</script>
Enter fullscreen mode Exit fullscreen mode

querySelectorAll

querySelectorAll is used to return all elements (as a NodeList object) that matche the giving css selector.

<div>Hi</div>
<div>Bonjour</div>
<div>Salam</div>
<button onclick="changeColor()">To Blue</button>
<script>
const changeColor = () => {
  document.querySelectorAll("div").forEach(div => div.style.color="blue")
}
</script>

Enter fullscreen mode Exit fullscreen mode

Summary

  • getElementById: for selecting an element using his Id
  • querySelector: for getting the first element that matches the giving css selector
  • querySelectorAll: for returning as a NodeList object All elements that matche the giving css selector.

Happy codding!

Discussion (13)

Collapse
lukeshiru profile image
LUKESHIRU

You can use querySelector instead of getElementById, like this:

document.querySelector("#id");
Enter fullscreen mode Exit fullscreen mode

Still, nowadays is a good practice to avoid IDs altogether, mainly because they aren't as flexible as classes.

Collapse
inhuofficial profile image
InHuOfficial

IDs are still useful so be careful with sweeping statements like “avoid IDs altogether”.

Especially important in accessibility for WAI-ARIA for example to associate controls with each other.

I agree with the sentiment of preferring classes over IDs, just thought I would add some clarity as people take things at face value!

Collapse
lukeshiru profile image
LUKESHIRU

Yup. I used the word "avoid" as "try to use as little as possible", sorry for not being clear enough (english is not my native language 😅).

Collapse
ayabouchiha profile image
Aya Bouchiha Author

Me too I prefer classes :)
Thank you a lot!

Collapse
masedi profile image
Edi Septriyanto

In my opinion, I agree with this statemen 👇🏻

"IDs are perfectly fine. How to improve it is just personal opinion. IDs and classes have their separate usage areas, which in some cases overlap. For automated testing, and CSS, ID's are extremely useful. Never be afraid to use them!"

Collapse
lukeshiru profile image
LUKESHIRU • Edited

Again, my point is that you should try to avoid them as much as possible, not that you should NEVER use them. For automated testing, there are better tools than selecting by id that force you to make elements more accessible (like selecting by title, for example), and even if you really need to identify an element and a11y isn't an option (it should always be), then you have data-testid which doesn't have conflicts like id does. For CSS ideally you should use classes (together with CSS modules). Unique identifiers aren't the best option. The main use ids have nowadays is like mentioned above, to link form elements together:

<label for="name">Name</label>
<input id="name" />
Enter fullscreen mode Exit fullscreen mode

Which is useful when they aren't next to each other, because when they are actually next to each other, you can just do:

<label>Name: <input /><label/>
Enter fullscreen mode Exit fullscreen mode

And screen readers also understand it. Is not "being afraid" of using ids, is just not using something that can generate unnecessary conflicts that you can avoid by just using better tools (like classes).

Collapse
ayabouchiha profile image
Aya Bouchiha Author

I agree with you

Collapse
ayabouchiha profile image
Aya Bouchiha Author

Absolutely true, I have mentioned that querySelector is used to return the first element that matches the giving CSS selector.
Thank you and have a nice day!

Collapse
efpage profile image
Eckehard

It is not recommended, but you can use ID´s without any selector at all:

<h1 id=myhead>Headline</h1>
<script>  "use strict";
    myhead.textContent = "New Headline"
</script>
Enter fullscreen mode Exit fullscreen mode

This is a common standard on all browsers that all ID´s are defined as global variables, so they can be accessed directly or as a property of the window-object ( -> window.myhead.textContent = "test"). It is not recommended to use this method, as the definition only works as long as there is no conflicting definition in the source. This script gives you an error:

<h1 id=myhead>Headline</h1>
<script>  "use strict";
    myhead.textContent = "New Headline";
    let myhead;
</script>
Enter fullscreen mode Exit fullscreen mode

--> "ReferenceError: Cannot access 'myhead' before initialization"

Maybe it´s woth to know...

Collapse
ayabouchiha profile image
Aya Bouchiha Author

Never heard about that, Thank you so much for the information!
Have a nice day!

Collapse
efpage profile image
Eckehard

Yes, it is a bit strange feature you should not rely on. There is a global variable for every ID - as long as it is not conflicting with something. In the example above, it is conflicting with a variable, there might be ohter names like classnames etc.. In any case you can access the ID with getElementById without those conflicts.

Collapse
khajin1 profile image
evalPenny

In the title, change commun to common

Collapse
ayabouchiha profile image
Aya Bouchiha Author

Thank you so much