Skip to main content

Command Palette

Search for a command to run...

Separate your Javascript Access from CSS Selectors

Published
β€’7 min readβ€’View as Markdown
Separate your Javascript Access from CSS Selectors
A

professional div renderer

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 πŸ“–

C

Great article!

P.S: I also love the article image!

3
A

Thanks, Catalin 😊 for reading it. I made the image myself πŸ’‘

G

Thanks for sharing this.. it would help me a lot.

2
A

Glad to help

1
B

Great blog

4
V

Thanks for highlighting the importance of readability in code! Great article too :)

4
A

Thank you, Victoria πŸ™. I appreciate it.

2
V

I use a different approach with a js prefix class. Attributes should be used to pass data and not for targeting element even so it's better than targeting an ID or a CSS class.

e.g:

<button class="js-percentage-button btn-red">%</button>
const percentageButton = document.querySelector('.js-percentage-button')
4
A

Indeed Victor, I too love to use that approach but what I realized is that selecting elements with data attributes can greatly improve the code readability and maintenance. Thanks for reading it πŸ’–

2
F

Thanks for sharing, I recently ran into an issue where I had to change my class name in both my HTMl and JS file. Now I'll use the data- attribute instead.

Also I like the way you write 😊, easily to understand πŸ‘

2
A

Thanks, Jome for your kind words πŸ™

1
S
Syarif5y ago

Very interesting topic, But don't you think that just by adding another class name only for JavaScript selector, give you the same approach?, thanks.

2
A

Yes Syarif, you're absolutely correct but IMO a class should be used for styling elements, but again these are just personal preferences. Thanks for reading it πŸ’–

A

Wow, amazing content and representations as well. I was feeling like you're talking when you used "not convinced Ayush"

6
A

Thank you, Akash πŸ’—

D

I am a Pythonic Guy, but I loved reading it. Your article really taught many things related to CSS and JS.⚑ I appreciate your article and the usage of simple words🌻

All the best for everything πŸ’―

4
A

Thank you so much Manish for your kind words πŸ’—

3

More from this blog

Ayush's Blog

8 posts