Id, classes, attributes, and tags

Hey ,

I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.

Please upgrade (use this link) access this content.

I'm super eager to help you learn more!

Id, classes, attributes, and tags

You learned that you can select elements with id, classes, tags or even attributes. Which ones should you use?

The factors

What you use depends on two factors:

  1. Whether you have control of the HTML
  2. The number of elements you need to select

If you don’t have control over the HTML, you kinda have to hack your way around the selectors. Nothing much you can do about it here.

If you have control over your HTML, you’ll want to pay attention to the number of elements you need to select.

If you only have one element

If you only need one element, always use id. This is because id defines a unique identifier in the entire document. You can’t have two elements with the same id.

If you have more than one element

If you have more than one element, you can choose between classes, attributes and tags. Most of the time, you’ll want to use classes or attributes. Avoid tags.

Why avoid tags

Tags are too generic.

Let’s say you have the following HTML. Would it be easier for you to select .component with tags or classes?

<div>...</div>
<div class="component">...</div>

Classes vs attributes

Classes and attributes are similar. You can use either. What you use depends on your use case. Usually, classes are used to select elements initially, and attributes are used to filter through them.

You’ll learn which ones to use as you build components through the course 🙂.

JavaScript hooks

It can be helpful to include a js prefix for components that requires JavaScript to work. This tells developers that JavaScript is required at a glance, and prevents you (or your fellow developers) from breaking JavaScript functionality when you change the class of a component.

<div class="component jsComponent">...</div>

Note: we won’t do this for the components we build in this course.