1

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?

Progman
  • 16,827
  • 6
  • 33
  • 48
Arcturus
  • 35
  • 6
  • 1
    Where will you use this value? Can you use javascript to get this value? – Bunny Oct 16 '22 at 14:31
  • @Bunny Hi! sorry for the late reply, lets say i just want to get it for some basic automation, if it possible to get the value using js, then how? – Arcturus Oct 17 '22 at 05:29

1 Answers1

2

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
});

Bunny
  • 1,180
  • 8
  • 22
  • Thank you for the answer sir!, can i apply this on DomHTML? – Arcturus Oct 17 '22 at 13:45
  • If you have an html file with a `script` tag pointing to a javascript file containing my code, then yes. You can also execute my code directly in the developer console. – Bunny Oct 17 '22 at 13:59
  • the html file will be coming from a different website url, and I want to get the value of data-target-id attribute to log it on console. – Arcturus Oct 17 '22 at 14:15
  • In that case, go directly to the website and open [Dev tools](https://developer.chrome.com/docs/devtools/open/) (F12 or CTRL + SHIFT + I). Go to the `console` panel and paste my code. Press Enter. – Bunny Oct 17 '22 at 16:43
  • Hi! sorry for my late reply, but what i want is use domhtml to my php code to get the html file of a website and do some basic task using the value that I will get to the said attribute and use it somewhere else. – Arcturus Oct 18 '22 at 04:53
  • 1
    What you described is web scraping. I'm not familiar with PHP but I've found [this post](https://stackoverflow.com/questions/9813273/web-scraping-in-php) which might help you. There are also external libraries which can simplify web scraping. – Bunny Oct 18 '22 at 07:24