Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla Javascript: Find a data attribute of the same name as an element given its id

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.

like image 796
HannahBanana Avatar asked Apr 11 '17 01:04

HannahBanana


1 Answers

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

like image 155
Hari Lamichhane Avatar answered Sep 28 '22 16:09

Hari Lamichhane