I am trying to solve a problem, where I am not allowed to use ID / CLASS selectors but must use data attributes.
I need to show and hide elements based on the selection from a drop down. The catch is that there are some items that can be shown alongside other elements, and some that are strictly to be shown alone / with specific elements. I have created a Pen to make it easier to understand:
Basically, if the data attribute has ‘OR’ then you can show one element or the other (within the data attribute list).
If the data attribute has ‘AND’ then it must show the selected item AND the other element in the data attribute list.
I hope this makes sense. I am like 80% there, but I know my logic is a bit dodgy and would love to find a cleaner solution! Thanks
Ok, I have solved the issue using a JSON object in the data attribute for the select field and for each DOM element. Here is the full example, as you can see the HTML is hard to read cause its all auto generated with PHP. But The JS logic is hopefully a bit more readable.
I didn’t know this, but data attributes can hold objects and arrays! On the select element I created a data attribute to hold a JSON object, like so:
Cool example of how data-attributes could be used! Thanks for posting the working example.
I’m a beginner when it comes to javascript but since you’re already working with jQuery wouldn’t another solution be to use attribute selectors and look for ‘keywords’ within the ID’s?
Yes, you’re totally correct. The “usual” way to do this would just be to use ID selectors. But I needed this to be a bit more flexible, as there would be multiple items that show at the same time. Plus I wasn’t allowed to use ID selectors because this needed to be a function that was easily reuseable across the codebase.
A good tip to remember every time you build something ---- Ask yourself, how reuseable is this code? Does it totally depend on specific DOM elements, or can I build this function so it works with any DOM element
Does it totally depend on specific DOM elements, or can I build this function so it works with any DOM element?
At this point I’m just happy to get things working ( ) but you make an excellent point. Also just saw your roadtrip app and now I really can’t wait to get started with vue, stay awesome!