0

I'm looking at three custom HTML attributes within an "a" tag and I'd like to extract their values into 3 separate javascript variables.

Here's the HTML with the attributes "data-event-category", "data-event-action", and "data-event-label":

    '<a data-event-category="Billionaire" data-event-action="SeeMore" data-event-label="Biography" href="xxx" class="ga-track-click billionaires-individual-see-more gotham-medium red-txt">Contact us to see more Biography</a>'

And this is the function I cobbled together, unsuccessfully trying to extract the value of "data-event-category":

     `function myFunction3() {
var z = document.getElementByClass(".ga-track-click").getAttribute("data-event-category");
return z;
       }`

Here's my fiddle :

https://jsfiddle.net/comicosp/430350g0/#&togetherjs=tGRIiss2gB

Can you please tell me the** correct way to extract the values of the 3 custom HTML attributes**?

** DUPLICATE ISSUE**

I can see how :

What do querySelectorAll, getElementsByClassName and other getElementsBy* methods return? would be similar, but I'm not sure how it applies to my question. I'm very very beginner with javascript.

Omid Reza Heidari
  • 658
  • 12
  • 27
comicosp
  • 1
  • 2
  • Why is this tagged [tag:getelementbyid] when you aren't using that function? – Quentin Jun 15 '17 at 18:33
  • https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes – epascarello Jun 15 '17 at 18:34
  • @Quentin not sure, honestly. I just thought it was relevant to getElementById... I've removed it. – comicosp Jun 15 '17 at 18:37
  • There is no getElementByClass – epascarello Jun 15 '17 at 18:38
  • This is not technically a duplicate as marked, he just had a mistake that is addressed in the other question. @LeonardoSaraceni You need to use `querySelector` instead of `getElementByClass`, or remove the `.` from your selector. – dlsso Jun 15 '17 at 18:43
  • User "WhackyWhale" figure out that I should be using document.querySelector(".ga-track-click") instead, so this is fixed!! Thank you, WhackyWhale!!! See the Fiddle link for the working answer. – comicosp Jun 15 '17 at 18:44
  • 1
    It should work at that point, but the best way to access the data is like this `var z = document.querySelector(".ga-track-click").dataset` now `z` will be an object containing all 3 bits of data. Or if you just want one you could get it by using `dataset.eventCategory` – dlsso Jun 15 '17 at 18:46

1 Answers1

0

Change

getElementByClass

to

getElementByClassName

or use

querySelector
ColdHands
  • 947
  • 8
  • 28