Is it possible to find an element that has a data attribute with the same name of an element's id in the DOM? (Is it a bad practice to give a data attribute the same value as an id?)
Example syntax:
HTML:
<li id="tab-1"></li>
<p data-tab="tab-1">Content 1</p>
Would be curious as to how to accomplish this in Vanilla Javascript. Thank you ☺
Edit: I am hoping to make my code so that if I have the ID of the element, I can just look for a data attribute of the same value if I don't have it off the top of my head.
Yes, you can do that. Here's how you do it:
var usingId = document.querySelector('#tab-1');
var usingDt = document.querySelector('[data-tab="tab-1"]');
console.log(usingId);
console.log(usingDt);
<li id="tab-1">Tab</li>
<p data-tab="tab-1">P Tab</p>
Is it a bad practice?.Nope
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