Arcturus
Arcturus

Reputation: 35

Html, Get the attribute data without using id and class name of div

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

Answers (1)

creme332
creme332

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

Related Questions