About cookies on this site

We use cookies to collect and analyse information on site performance and usage, to provide social media features and to enhance and customise content and advertisements. Learn more

Cookie settings

About cookies on this site

Cookies used on the site are categorized and below you can read about each category and allow or deny some or all of them. Learn more

Necessary

Some cookies are required to provide core functionality. The website won't function properly without these cookies and they are enabled by default and cannot be disabled.

Preferences

Preference cookies enables the web site to remember information to customize how the web site looks or behaves for each user. This may include storing selected currency, region, language or color theme.

Analytical cookies

Analytical cookies help us improve our website by collecting and reporting information on its usage.

Marketing cookies

Marketing cookies are used to track visitors across websites to allow publishers to display relevant and engaging advertisements. By enabling marketing cookies, you grant permission for personalized advertising across various platforms.

  • Courses
    • Paid courses
    • Course bundles
    • Free courses
  • Blog
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • Services
  • About
    • About
    • Contact
  • Login
  • Courses
    • Paid courses
    • Course bundles
    • Free courses
  • Blog
  • Resources
    • Youtube channel
    • E-books and Guides
    • GTM Recipes
    • View All Resources
    • GTM Community
    • GA4 community
  • Services
  • About
    • About
    • Contact
  • Login

March 18, 2025

DOM Element variable in Google Tag Manager

Updated: March 18th, 2025

In this blog, I’ve already published articles about various Google Tag Manager variables, e.g., Auto-event variable, URL variable, Undefined variable, etc. But there’s one more that did not get a lot of publicity here, the DOM Element variable. That’s because it requires some technical knowledge, and I’m not its biggest fan (due to its fragility).

Those who have read my articles for a longer period know that I always advocate for having data in the Data Layer rather than trying to scrape something off the website. However, not all projects are perfect, and not all of them have dedicated development resources. Therefore, we might end up scraping DOM or using CSS selectors in our triggers.

That’s why I think that you should still know what the DOM Element variable is and how to use it.

Table of contents

  • A quick introduction to DOM
  • Configure the DOM Element variable in Google Tag Manager
  • What if the ID is not present? Enter the zone of CSS Selectors
  • How to test your CSS Selector
  • Risks
  • How is the DOM element variable different from the Auto-event variable?
  • Final words

 

Before we continue: this topic is also thoroughly covered in the Intermediate Google Tag Manager Course

DOM Element variable is one of those features that intermediate Google Tag Manager users often overlook (or just accidentally skip). That’s why I have created an Intermediate Google Tag Manager course that will take your tag management to a whole new level (uncovering the potential of GTM).

Enroll in Intermediate Google Tag Manager course

Also, you can learn much more about JavaScript for Google Tag Manager in my other course.

 

Video tutorial

If you prefer learning from a video, here’s a tutorial that will teach you how to scrape the website (and one of the methods is using a DOM Element Variable).

 

A quick introduction to DOM

To understand the DOM Element variable in GTM, you first need to have at least a very basic understanding of what DOM is in general. Document Object Model (a.k.a. the DOM) is a dynamic tree-like hierarchical representation of the website’s document. It allows manipulating the website’s document, getting values of current website elements, adding new, editing, or removing existing ones.

If you go to any website and open its source (e.g., CTRL+U on Chrome (WIN)), you’ll see the HTML code of the page. This is the code that a developer wrote to make the website look the way it does right now.

But it does not look very dynamic, does it? But if you go back to that very same website and open developer tools (Chrome on Windows: press F12, Chrome on Mac: Command + Option + I), you’ll see a more dynamic representation of the website’s code. If not, switch to the Elements tab.

There are nodes that can be expanded or collapsed (by clicking dark triangles), many nodes have children that can have their own children, nodes can have multiple children, etc. It’s a dynamic tree-like representation of the website’s documents. You’re inspecting the HTML DOM here.

As I have mentioned before, DOM allows not only viewing/inspecting of website elements but also manipulating them as well. The easiest and most down-to-earth way to edit nodes in the DOM is to double-click on a certain node and then change its value or delete/edit/add attributes to an element.

But this is not very scalable and useful. Instead, there should be a better way to do that, right? Yes. DOM supports a bunch of methods that enable developers (and you, if you are skilled enough) to add, edit, and delete elements.

As for reading values, getElementById(“some_id”) method will return you the first website element that matches a some_id ID. In the screenshot below, you can see the command (1st line) and the returned element (2nd line).

Another example could be querySelector(), which returns the first website element that matches a certain CSS Selector defined by you.

And that’s a good moment to introduce Google Tag Manager’s DOM Element variable. This type of variable can access the value of a website element that matches a condition defined by you. Let’s take a closer look.

Subscribe and Get the Ebook - JavaScript for Google Tag Manager

Configure the DOM Element variable in Google Tag Manager

To create a new DOM Element variable, go to Variables > Scroll down > New > DOM Element. Click it, and let’s take a look at the possible settings here.

The first thing you need to set is the selection method. You need to tell GTM somehow which particular website element you are interested in. Elements can be selected either by an ID or by a CSS Selector. First, let’s try ID.

Let’s imagine that we have a page with a particular product, and you want to get the name of that product. One of the ways to do that would be to read the text of a website element, that is the Product Title. Right-click on a product title, and let’s hope that we’re lucky enough to find an ID in that element. Bingo!

Double-click that ID, copy and paste it into the Element ID field in your GTM variable. What about the 2nd field (Attribute name)?

If you leave it empty, the DOM Element variable will return the website element’s text (in this example, Dark Blur T-Shirt). However, in some cases, it might be more useful to fetch not the text of an element but its certain attribute. You can find out what attributes a certain web element has by inspecting it (this time, I inspected a different element).

See all these highlighted parameters (type, name, id, class)? They are called attributes.

So if you want to get the value of a particular attribute, you’d need to specify its name in the field Attribute Name, e.g. type.

To see whether your variable has been created properly, save it, enable/refresh the Preview and Debug mode, and check the variable’s value in the Variables tab.

 

What if the ID is not present? Enter the zone of CSS Selectors

If you’re not familiar with CSS Selectors yet, I explain them in my intermediate/advanced GTM course.

In a nutshell, CSS Selectors allow targeting specific website elements to apply a style to them (after all, CSS is for styling the website). Here’s a basic example of CSS:

.red-button {
color: #FF0000;
}

This piece of CSS states that all elements containing the class attribute red-button will be colored red (color code #FF0000). Targeting elements in CSS is possible thanks to CSS Selectors. In the example above, the CSS Selector is .red-button, and it targets all elements of which class is red-button (a dot in CSS means “class”).

But CSS selectors are so versatile that they can be used in DOM Methods too. If you want to pick a certain website element and read its value, you can write a more complex CSS selector, for example, div.call_to_action > .someClass.

document.querySelector("div.call_to_action > .someClass")

 

How to test your CSS Selector

Let’s say that you have finally managed to write a CSS Selector that targets some important element. How can you test it? One way could be to save the variable in the GTM interface, refresh the preview mode, then refresh the page and check the variable’s value. But that’s a long path.

What if you fail to create a proper CSS Selector the first time? What if you end up tweaking the selector 20 times? You’ll have to save the variable, refresh the preview, and test 20 times. That’s where the time is wasted.

A quicker alternative is to use a document.querySelector() method in the JavaScript console of your browser. Just open it and enter the following command:

document.querySelector("your_css_selector")

Replace your_css_selector part with your actual selector. Hit enter, and (if your selector is correct) it will return the element that you wanted to target. If you get some unexpected results, tweak the CSS Selector and try again.

When you finally get the desired result, do the final test by entering the CSS Selector in the DOM Element variable’s settings (in GTM UI).

 

Risks

I can’t emphasize enough the risk of using DOM to fetch values of website elements. If you plan to scrape the DOM in your tracking implementation heavily, you need to be aware that a developer can unknowingly change something in the website’s content that can break your DOM Element variables within GTM. The more complex/longer your CSS selectors are, the higher chances of breaking updates will be.

If, for some reason, a developer changes a certain class of an element (and you’re using that in your selectors), your DOM Element variables will start returning null. Hence, your tracking will break.

So before you use CSS Selectors (and DOM Element variable in general), you need to weigh your options and the current situation. The chance of breaking changes is lower if the website is not constantly updated. But if developers are regularly pushing for improvements and A/B tests are running every day, maybe you should consider getting data in other ways (rather than scraping the DOM).

What is the other way? Your best option is the Data Layer. Ask a developer to push some important information to the Data Layer and use that in your tag management. From what I’ve seen, the chances of breaking Data Layer changes are much lower than with DOM scraping.

I completely understand the temptation of using CSS Selectors now. So much power and independence from developers, right? I’d even like to borrow the meme from Jim Gordon:

But in the long run, Data Layer always wins. Actually, you should read the full blog post by Jim about this topic.

 

How is the DOM element variable different from the Auto-event variable?

If you are familiar with another GTM variable, the Auto-event variable, you might be wondering how the DOM Element variable is different from AEV.

The auto-event variable allows you to fetch the text (or an attribute) of an element that a visitor/user has interacted with. If a visitor clicks a link, you can access that element’s properties.

DOM Element variable lets you access any element that is present on a page. That way, you can get its text or value of a certain attribute. No interaction is required. In fact, here’s an example of a risky form-tracking technique where successful form submission is counted when a success message element is present on a page. This was done with the help of the DOM Element variable.

 

DOM Element variable: Final words

DOM Element is a nice tool in your GTM toolkit. However, you should not abuse it. It is a flexible way of fetching particular data on a page, but if the page content/design often changes, your DOM Scraping efforts have a high chance of failure.

In fact, very recently, in the Google Tag Manager community on Facebook, we had a case where one of the members did not understand why suddenly one of his events was not properly tracked in GTM. Turned out something was changed on a website, and it broke his CSS Selectors.

So if you’re interested in getting some custom data and making it accessible in GTM, a developer and dataLayer.push should be your best friends.

Julius Fedorovicius
In Google Tag Manager Tips
14 COMMENTS
Andy
  • Mar 19 2019
  • Reply

Hi,

We've got a multi-div form that I'm trying to track through each section. The only easy I can see to track each stage is using the DOM element method. The .form-section.current > h1 changes when you click to the next section.

I've tried to set a trigger as DOM element visibility and to monitor the DOM for changes but it only picks up the first time it becomes visible.

Any ideas? Can supply GTM code variables etc.
Getting very frustrated with it.

    Julius Fedorovicius
    • Mar 19 2019
    • Reply

    Hey, DOM Element variable is re-evaluated every time a new event happens in the Data Layer (incl. your Preview and Debug mode). So if something changes in the multi-div form, you need to make sure that some event appears in the Data Layer.

    1. If the URL changes (without page reload), you could try using History Change trigger. I use that trigger here https://www.analyticsmania.com/post/single-page-web-app-with-google-tag-manager/
    2. If the form is AJAX, you could use AJAX listener https://www.analyticsmania.com/google-tag-manager-ajax-form-tracking/
    3. If divs appear one after another, maybe you could use Element Visibility trigger https://www.simoahava.com/analytics/element-visibility-trigger-google-tag-manager/
    4. You could try to observe DOM mutations (I haven't tried it though https://www.simoahava.com/analytics/google-tag-manager-dom-listener/)
    5. You could ask a developer to push the event to the Data Layer when user moves from one step to another (but if you manage to get developer's time, then ditch DOM Element Variable and ask for some additional data in the Data Layer as well https://www.analyticsmania.com/post/datalayer-push/)

      Prajwal Adappa
      • Aug 26 2021
      • Reply

      Hi Julius,

      We're trying to setup a DOM element variable to retrieve information on Order ID. We're using a SPA and the following happens on purchase.

      A purchase event is triggered with a dataLayer push but the order ID is not something useful as it's a randomnly generated string. While we do not want to wait on the developers we do have the right order ID visible on the page. I tried using the DOM element variable and provided the CSS selector. However, since it's a SPA, there is a DOM reload happening.

      The CSS selector is working as I verified this by reloading the page completely and the value becomes available on DOM ready.

      We do have a pageview dataLayer push just after the purchase event but that doesn't seem to help.

      Could you please let me know if there's a way to capture this information either on the purchase event or the pageview event.

      Thanks much as always.

Robin
  • Aug 5 2020
  • Reply

Hey Julius. Really useful article... Thank you. Having created my DOM Element variable (with 'Selection Method' ID), I would like to trigger an Event in Google Analytics, pulling in the Click Text. How would I do this? Any help would be appreciated.

    Julius Fedorovicius
    • Sep 16 2020
    • Reply

    Hi, I don't understand why would you need to use DOM element variable while tracking Clicks. Use either the built-in click variables or the auto-event variable.

Milica
  • Aug 26 2020
  • Reply

Hi Julius, how can I get the value of the color as a varible:

.siteLink{
color:#006666 !important;
}

    Julius Fedorovicius
    • Aug 26 2020
    • Reply

    Hi, can you describe a situation where you need this? I want to write a tutorial about it but I must understand the need and the context first. Why is it valuable for you to know the color of the element? What kind of insights do you expect to get from this?

Wendy
  • Nov 9 2021
  • Reply

I created a DOM element variable for and tags.
For some reason, the value remains the same for all clicks, and that does nor represent the actual situation observed amongst the different links clicked. Why would this happen and is there a resolution.

    Julius Fedorovicius
    • Nov 10 2021
    • Reply

    That's exactly how DOM element variable is supposed to work. It does not care about clicks. It just takes the first element that matches your condition on a page, regardless of user interactions.

Abel
  • Nov 13 2021
  • Reply

I need to track all my post tag.
When page load or page view, send all tag to GA4.
I know how to get one element by id or class and send it to GA4.
But is there any way to send all tag value on page view or page load?

Mahmoud
  • Dec 5 2021
  • Reply

Hi Julius. Really useful article... Thank you

Could you tell me what is wrong with using chrome DEV tools by hover over on the desired element and use "copy css selector" instead of writing css selector in tag manager ?

Anthony
  • Dec 7 2021
  • Reply

Is there a way to grab a href TITLE using GTM?

    Julius Fedorovicius
    • Dec 21 2021
    • Reply

    Depends on what do you mean by that. If you are talking about the page title, use JavaScript variable document.title

Brianna
  • Jan 5 2023
  • Reply

Hey Julius,

Thanks for the useful articles! I'm trying to set up a listener for an HTML5 video player (and I followed your tutorial at https://www.analyticsmania.com/post/track-html5-video-player-with-google-analytics-4-and-google-tag-manager/), but I'm getting stuck at the variable.

Though a video object is present on the page (I verified the exact same DOM navigation in Inspect's Console), GTM keeps returning 'false.' Which is how I ended up here to attempt a boolean check against the DOM object directly (instead of using cjs). But that, too, is returning 'null.'

Do you have any suggestions on what I can troubleshoot so I don't have to just have the listener fire on every page?

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *


 

Hi, I'm Julius Fedorovicius and I'm here to help you learn Google Tag Manager and Google Analytics. Join thousands of other digital marketers and digital analysts in this exciting journey. Read more
Analytics Mania
  • Google Tag Manager Courses
  • Google Tag Manager Recipes
  • Google Tag Manager Resources
  • Google Tag Manager Community
  • Login to courses
Follow Analytics Mania
  • Subscribe to newsletter
Recent Posts
  • Google Analytics 4 User ID for cross-device tracking: how to configure it
  • How to Track QR Codes with Google Analytics 4
  • The Magic of Cookies with Google Tag Manager
Analytics Mania - Google Tag Manager and Google Analytics Blog | Privacy Policy
Manage Cookie Settings