
The . and # selectors are the keys to selecting elements in JavaScript.
In CSS selectors, a period(.) is used to target elements by their class name, while a hash(#) is used to select elements using their id.
When using JavaScript to manipulate HTML with document.querySelector(), these same selector mechanisms apply:
Use
document.querySelector('.className')to select elements by class.Use
document.querySelector('#idName')to select elements by id.
Why might we choose class or id?
If multiple elements share the same style or behavior, you typically use a class. Since classes involve multiple elements,
document.querySelectorAll('.className')could be useful to select all occurrences.Ids, being unique, are great for elements that should stand out or be isolated. Only one element should have a particular id on a page.
Take a look at the following code:
// Target an element with a class of 'button'
const btn = document.querySelector(".button");
// Changes text content of elements of 'button' class
btn.textContent = "Claim Discount"Since we've used a . selector here, the JS code targets the specified class (in this case, the button class).
Remember: It's all about how the HTML element has been marked up on your page!
Our Experts
Sudip BhandariHead of Growth/Marketing
Apekchhya ShresthaSenior Product Manager
Kelish RaiTechnical Content Writer
Abhilekh GautamSystem Engineer
Palistha SinghTechnical Content Writer
Sarthak BaralSenior Content Editor
Saujanya Poudel
Abhay Jajodia
Nisha SharmaTechnical Content Writer
Udayan ShakyaTechnical Content Writer
