Simple javascript code to extract the "data-href" in the below HTML anchor script for Google Tag manager(GTM)

What have you tried? Are you unsure how to select this, or how to get those data attributes? This might help DevDocs

1 Like
const tags = document.querySelectorAll('a');
const matches = tags.forEach((tag) => tag.getAttribute('data-href'));

Try it out

// Edit

its not working please check it once

The idea is to target the tag and loop throught its attributes, when it find right attribute just return its value, We can’t see your code so it’s hard to say where you made mistake. Just embde the code after google tag manager script.

is the above format is right… GTM have some restrictions we need to write code within tag and it mandatory to contain function and return value…

I imitiated your environment to make sure that code will work, try out the below code.

const tags = document.querySelectorAll('a');
const matches = [];
for (const tag of tags) {
	const match = tag.getAttribute('data-href');
	if (typeof match === 'string') matches.push(match);

when you place this code in function don’t forget to invoke it.

In that one tag, with the Download string? It might be as simple as:

const myAnchorsHref = document.querySelector("a:contains('Download')").dataset.href;

The first half simply selects that element, and the dataset.href identifies the data attribute you wish to retrieve.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.