Vanilla Javascript: Find a data attribute of the same name as an element given its id
Solution 1
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
Solution 2
If you are trying to select an element having an unknown html5
data-*
attribute using the .id
string property from a different element, you can query all elements in document
, check the .name
and .value
of each elements' .attributes
, if .value
of attribute is equal to .id
of element which provides .id
and .name
of the .attribute
property is not "id"
, the element is matched using attribute equals selector at .querySelector()
<li id="tab-1"></li>
<p data-tab="tab-1">Content 1</p>
<script>
let id = document.getElementById("tab-1").id;
for (let el of document.querySelectorAll("*")) {
for (let {name, value} of el.attributes) {
if (value === id && name !== "id") {
document.querySelector(`[${name}="${id}"]`)
.style.color = "green";
break;
}
}
}
</script>
HannahBanana
Updated on June 10, 2022Comments
-
HannahBanana about 2 years
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.