I have multiple DIV
items on the page that users can select, and what I have implemented in my JavaScript code is that when an item was selected, I added a CSS class to it to flag that it is a selected item and then later use it to apply business rules logic around it.
That was just an example, but in general however, I am wondering if I should be using the class in this way, as the class itself does not change the presentation of the page in any way, and the intention of CSS classes were for presentation purposes. Is doing it this way a case of mixing presentation and business logic, which is considered not a good design pattern?
Furthermore, it might trigger the browser to perform some presentation processing overhead when the class is added and possibly slow things down.
I was wondering if what I should be doing instead is adding state information as a custom attribute to the DOM
element?
In general it is not wrong to do so. Frameworks like jQuery are amongst other things built around the use of class attributes.
However, as of HTML5 there is a more elegant solution for most cases, which is the so called data properties.
This allows you to add any arbitrary property to your HTML tag if you prefix it with data-
.
An example would be:
<div data-value="3">Amount: $3.00</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With