If you’ve been coding for a while, I’m sure you’ve seen many cases where JS used the same class selector as CSS as shown below.
<div class="nav_toggle">some more code...</div>
.nav_toggle {
position: relative;
width: 35px;
overflow: hidden;
white-space: nowrap;
color: transparent;
}
const nav_btn = document.querySelector('.nav_toggle');
Technically speaking there is no harm in doing this, lots of programmers do it all the time as I used to do it too.
Doing that makes code a little harder to maintain since now you have JS depending on a class to target a specific element and expects that class to stay there.
As you know there are a lot of times when we need to add and/or remove classes in HTML elements.
And you shouldn’t have any issues as long as the needed classes by JS stay in the file, but there’s a better and cleaner way.
Using Data Attributes as JS Selectors
The Best selector for JavaScript is the data attribute, and the reason is that they are very dynamic.
A data attribute can hold data which is a great advantage, and now you can also focus on adding elements with more standard classes so you can repeat those classes as needed to write way less CSS.
That’s the most effective way to write code, trying to make reusable CSS so the file stays as small as possible and separating JS selectors so the code stays clean, organized, and easy to maintain.
The idea is to separate functionality, classes style the elements with CSS and data attributes to make the page dynamic.
<div data-nav-toggle class="nav_btn">some more code...</div>
const nav_btn = document.querySelector('[data-nav-toggle]');
I would also recommend you to read “Why You Shouldn’t Use Class Selectors In JavaScript” by Kyle from WDS.
What are your thoughts on this, leave your opinion in the comments below.
Im very pleased to uncover this page. I want to to thank you for your time just for this fantastic read!! I definitely appreciated every little bit of it and i also have you saved to fav to look at new stuff in your web site.