Reputation: 35
I would like to ask if its possible to get such value:
Here is the sample div
<div class="" data-target-id="VALUE" data-id="legacy"></div>
In sample div, lets say I want to get the value of the attribute 'data-target-id'.
Is it possible using domhtml?
Upvotes: 1
Views: 890
Reputation: 1945
To access the value of a data attribute in JavaScript, you must use dataset
.
To select only the first div in DOM having a data-target-id
attribute and print its value :
const targetId = document.querySelector('[data-target-id]');
console.log(targetId.dataset.targetId); //VALUE
If there are more than 1 div having having a data-target-id
attribute, you can use querySelectorAll
instead of querySelector
then use a loop to print the targetIds.
If you want to select only div with a data-id="legacy"
, you can use this:
const divs = document.querySelectorAll('div[data-id="legacy"]'); //get all div with a data-id="legacy"
divs.forEach(div => {
console.log(div.dataset.targetId); //output corresponding target-id
});
Upvotes: 2