0d: 00h: 00m: 00s

🎁 Get 3 extra months of learning — completely FREE

That's 90 extra days to master new skills, build more projects, and land your dream job.

Become a PRO
Background Image

🎁 Get 3 extra months of learning completely FREE

Become a PRO
K vijay Kumar
2 months ago
Kcountry asked

What do . and # mean, and how do we use them in CSS and JavaScript?

Abhay Jajodia
Expert
yesterday
Abhay Jajodia answered

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!

This question was asked as part of the JavaScript in Browser course.