DEV Community

Discussion on: Vanilla JavaScript data attribute filters

Collapse
 
lexlohr profile image
Alex Lohr

Or you let CSS do the job and just create a style tag with the required definitions:

const ratingStyleContainer = document.createElement('div')
ratingStyleContainer.style.display = 'none'
document.body.appendChild(ratingStyleContainer)
const ratingSelector = (minRating) => [...Array(5)].reduce(
  (full, _, index) => index + 1 < minRating 
    ? [...full, `[data-rating="${index + 1}"]`]
    : full,
  [] 
).join(', ')
const showOnlyRatings = (minRating) => {
  console.log(ratingSelector(minRating))
  ratingStyleContainer.innerHTML = minRating > 1
    ? `<style>${ratingSelector(minRating)} { display: none; }</style>`
    : ''
}
const rating = document.getElementById('rating')
rating.addEventListener("change", () => showOnlyRatings(+rating.value))
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dailydevtips1 profile image
Chris Bongers

That's another way of doing it haha
Just wanted to showcase the interaction between javascript and data attributes again.

Collapse
 
lexlohr profile image
Alex Lohr

And it was a nice example. I just find that a lot of front end developers tend to use JS for everything, even if HTML, SVG or CSS are better suited to do the job. We're so pampered by our high-level frameworks that we easily forget the low-level stuff.

Thread Thread
 
dailydevtips1 profile image
Chris Bongers

Your right, there are so many options of doing certain things, might not always be the "best' solution sometimes it's indeed about finding the perfect solution for that specific time and use case.

Well said Alex!