Separate your Javascript Access from CSS Selectors

5 min read

Separate your Javascript Access from CSS Selectors

Do you use CSS selectors like classes or id's to select the HTML elements on the Document Object Model? If yes, then get ready to learn an more intuitive way to select the DOM elements because in this article we will be learning about how and why to use something called Data Attributes.

First Thing First - What are Data Attributes?

Wait, what is an Attribute?🤔

Attributes are the words that provide additional information about HTML elements. They are used inside the opening tag and normally come in name/value pair like: name="value". For example, in the code below, an image tag has an attribute named 'src' which specifies the path of the image to be displayed.

<!-- 'src' is an attribute  -->
<img src="./cat.jpg" />

Like the 'src' attribute there're many other attributes available in HTML that can be used to define the behavior of the element. But what if you want to use a custom attribute like: body-hair="fur"

<!-- 'body-hair' is not a HTML attribute  -->
<img src="./cat.jpg" body-hair="fur" />

but this isn't how you're supposed to do that because it is not valid HTML. Now here comes the role of Data Attributes, to make the above HTML valid, you just need to add data- before body-hair

<img src="./cat.jpg" data-body-hair="fur" />

Data Attributes

They can be used to store additional information that you don't want to be accessible to the client but are extremely useful for information that is not appropriate with class or id. Because class or id attributes are generally used for styling the page and it's always good to separate your styles from logic.

Back to our Question 🙋‍♂️

Usually, the most common ways javascript developers use to traverse the DOM element are by either getElementById('id-name') or querySelector('css-selector'). For example:

<div class="red-box">I see red everywhere</div>

To select the div, we can use:

const div = document.querySelector('.red-box');

Now, there is absolutely nothing wrong with selecting the above way, but again the main purpose of class="red-box" is for styling the div, not traversing the element via javascript. So instead of using CSS selectors, we can use data attributes to select the elements.

I'm still not convinced Ayush 😕

Alright, suppose for some reason I don't want the div to be red instead, I now want it to be blue. Now some of you may be thinking that it is no big problem. Just change the style accordingly from red-box to blue-box.

<div class="blue-box">I see blue everywhere</div>

But back there, we had also used the class red-box for grabbing the div, which is now invalid.

// This code is invalid, it will throw an error:
// Uncaught TypeError: div is null
const div = document.querySelector('.red-box');

You've to change it to:

// Now this will work
const div = document.querySelector('.blue-box');

Now, this still may not look like a problem because after all I just had to change one line of javascript. But practically, real-world applications may have literally hundreds even if not thousands of lines of code. This is tedious work because every time someone changes the styles (name of CSS selectors), you've to change the javascript also.

Enough talk, tell me how can I do that?

First, add a data attribute to the div and name it explicitly so that the other person looking at your code can easily tell what the information is about.

<!-- you can use them without specifying a value-->
<div class="blue-box" data-text-box>I see blue everywhere</div>

Now, write the following javascript:

const textBox = document.querySelector('[data-text-box]');

this will grab the div into textBox

Another Example:

<!-- A button to calculate percentage -->
<button data-operation="percentage" class="btn-red">%</button>

to select the above button, we can use the following code:

const percentageButton = document.querySelector(
  '[data-operation="percentage"]'
);

You can see that class of btn-red does not show what the element is meant for because it is only used for styling the button, but by using the data-operation="percentage", one can easily understand what is the function of the element.

My thoughts 💭

Separating bits of information that are needed for CSS and Javascript can greatly improve the readability and can reduce the time required for maintaining your code. And using Data attributes are a great and legit way to store that information semantically.

Little about myself 🧑

Hi, I'm Ayush, a sophomore CS undergrad student, and in my spare time, I'm a self-taught front-end developer and I believe in making the web accessible and a better place for everyone. This is my first blog post, if you find anything that I can improve on, feel free to write it in the comments. Thanks 💗! for reading. I would love to hear from you 🤝, my DM's are open on Twitter

Resources 📖

⚡ Originally published at ayushcodes.hashnode.dev

If you found this article helpful, I would be grateful for your support.
"Buy me some paneer curry"