Close this search box.

Top 5 Techniques in JavaScript for Google Tag Manager

Last Modified on January 4, 2024

Do you want to step up your measuring game? 

If you’re using Google Tag Manager, learning how to use JavaScript, the programming language GTM is built on, will without a doubt help you achieve your GTM success goals.

GTM For Beginners

Sign up to the FREE GTM for Beginners Course...

Even though hearing that coding or programming is involved may be daunting, we’re here to guide and teach you the essential commands that you should know if you want to be more effective and work faster and safer in GTM.

In this guide, we’ll share with you five advanced techniques in JavaScript for Google Tag Manager that all digital marketers should know.

These are the top 5 must-know techniques for Google Tag Manager:

  1. Data Layer
  2. Data Layer Push
  3. Query Selector Method
  4. Google Tag Manager Object
  5. Immediately-Invoked Function Expression

1. Data Layer

Let’s start with a straightforward but powerful command to access the Data Layer.

A website typically has three layers: the presentation layer – what your users see, the applications layer – made up of tools connected to the website (e.g. Google Analytics and Google Tag Manager), and the Data Layer – where user-generated data gets stored.

The Data Layer provides a reliable way of collecting data from your website. The values inside this layer are often used by Google Tag Manager to pass information to your tags.

These include events, variables, and triggers that can be set up based on the variables’ values.

If you or your developer placed the Google Tag Manager container JavaScript snippet (gtm.js) in your website’s source code, then the Data Layer is automatically created.

Let’s say a friend sends you their website and wants you to check if their tracking is working. Since the Data Layer is the basis of GTM, the first step to checking their tracking deployment should be to look at the Data Layer. 

A quick and convenient way to access the Data Layer, even without having access to the Tag Assistant, is to go to your browser’s Developer Tools

If you’re using Google Chrome, go to the applications menu → More Tools Developer Tools.

Accessing the browser developer tools

The developer tools for other browsers should be in a similar location. You can also use the keyboard shortcut Ctrl+Shift+I for Windows or Cmd+Shift+I for Mac.

Let’s move the developer tools pane to the side by clicking on the three dots at the top right corner, then the right-most icon for the Dockside option.

Docking the developer tools pane to the right

In the Console tab, type in dataLayer, then press Enter.

🚨 Note: JavaScript is a case-sensitive language. The dataLayer command should be entered with a small letter d, capital L, and with no spaces to properly access the Data Layer.

Entering the dataLayer command in the console tab

Clicking on the returned snippet will reveal all of the information stored in the Data Layer. Here, we can check if the right tracking information is properly stored.

Items stored in the Data Layer

When you click on the Add to cart button on any product, the Data Layer should be updated with the add to cart information.

Adding a product to the cart

To see the updated Data Layer information, we need to input the dataLayer command again. Here, we can see that there are now 7 items in the Data Layer, which includes the add-to-cart event.

Updated Data Layer information containing the add-to-cart event

💡 Top Tip: Pressing the up arrow key will copy the latest command you have typed in the JavaScript console.

Your troubleshooting can end here since you see that the Data Layer is set up properly or you can proceed and check other events.

If you need a quick way to check the Data Layer without extensions like the Tag Assistant, just type in the dataLayer command to your JavaScript console. 

2. Data Layer Push

The next command attached to the Data Layer is dataLayer.push, which is used to store data in the Data Layer. This command uses an object with a key and value pair as an argument.

To check how it works, type in the following Google Tag Manager code example:


Press Enter. This should then return true.

Sample dataLayer.push command

If we invoke the dataLayer command again, we will see the key-value pair as the latest object in our Data Layer that we can then use in our tracking.

Sample key-value object successfully pushed to the Data Layer

Now, when would it be useful to know a command like this? If you want to build a Data Layer and push custom information to it, then this command is something you need to learn how to use.

This command can be perfect if you only want to try out your tracking, and if you already have built tags that listen to a certain Data Layer event.

For example, the dataLayer.push command can send in a purchase event by invoking the next GTM code example:

Pushing a purchase event to the Data Layer

You can then view the purchase event in the Tag Assistant, as well as the information that was brought in.

Purchase event showing in the Tag Assistant

Inputting your dataLayer.push codes in the JavaScript console allows you to try them out beforehand and check if they are working properly before you implement them on your tags.

For example, if you wanted to install the enhanced eCommerce purchase tracking from the developers’ page, you can first try it out by copying the code and pasting it to the JavaScript console. 

Enhanced eCommerce purchase tracking code

You can then see how this code affects the Data Layer based on the message you get. 

Since this code returned true, it means it is working properly and will work fine when implemented in your tags.

Enhanced eCommerce purchase tracking code returning true

However, if you try out another piece of code and it returns an unexpected error, it means something is not right in your code.

Unexpected error in the copied code

Knowing that there is an error beforehand allows you to correct your mistake before you send it to your developer and implement it on your website.

To fix this error, first, click on the error code at the right.

Clicking on the error code

This leads us to where an error has been detected. We can see that one line has a red underline because the error was caused by the line before it. A comma was forgotten after the line which caused the whole thing to fail.

Lines in the code where the error was detected

To fix this error, we simply need to go into the code again and put in a comma at the end of the affected line.

Fixing the line of code causing the error

We’ll know if the code has been fixed if it returned true.

The true result signifying the error has been fixed

It is very handy to know about the dataLayer.push functionality to design your Data Layers, try out Data Layer syntax, and find errors, before you give it over to a developer and implement it on your website.

After pushing data/events to the Data Layer, you can then use the Data Layer event as a trigger and use the data to create your tags or variables.

🚨 Note: Check out our guide on scraping data with Chrome developer tools and GTM to learn how to inspect a website element and copy its JS path to create a GTM custom JavaScript variable.

3. Query Selector Method

The next technique we can use to utilize JavaScript for Google Tag Manager is the query selector method.

We have already discussed how you can pull data from and push data to the Data Layer, but what if the data you need for your tracking implementation is not in the Data Layer?

This method is very important for Google Tag Manager because it lets us select some aspects of the page that are present in the presentation layer. 

The presentation layer is made up of elements on the page that the user sees, and is built on HTML and CSS. To proceed with this method, you do need to have some background in CSS so that you know how to select an element.

As we’re trying to keep this discussion as digestible as possible, knowing how CSS selectors work will help you better utilize the selector method for your website and meet your specific tracking needs.

Let’s say you want to get the price of a product on the product page. Right-click on this element and select Inspect.

Inspecting the price element on the product page

This opens the developer tools on the elements tab where the HTML tag containing the inspected element is highlighted. Take note of the parent elements from the highlighted tag.

Inspected element code in the developer tools pane

What the query selector does is that it finds an element on the page and returns it to you, so that you can do further operations on it and transfer it over to Google Tag Manager.

Let’s now utilize the query selector command and test how the CSS selector works. To start, let’s pull the elements that have the price class. We need to use the class selector inside the query selector command with the syntax ‘.classname.’

Type the following code in the console tab, making sure that the CSS selector is enclosed in parenthesis and single quotation marks:


Press Enter. If we hover over the HTML element that the command returned, the equivalent element on the webpage will be highlighted.

querySelector command selecting all elements with the price class

This is a good start since the correct area is highlighted. However, aside from the price, other things are also included. Therefore, we need to dive deeper and be more specific about the CSS selector we use.

Let’s use two type selectors in conjunction with the descendant combinator to change our CSS selector to “.price span bdi”. This selects the <bdi> elements inside the <span> element under the elements with class = “price”.

Our command should now be:

document.querySelector(‘.price span bdi’)

Checking and hovering over the element returned from using the command now only highlights the price with the dollar sign.

Improved querySelector command selecting the product price

We can then only pull out the text inside the HTML element by adding .textContent at the end.

Grabbing the text inside the element using textContent

After testing it and knowing what it selects, we can then now use this CSS selector in different places inside GTM.

Let’s go over to Google Tag Manager and build something that will pull out that text exactly. For example, we can go and create a DOM element variable.

Go to VariablesNew.

Creating a new variable

Click on Variable ConfigurationDOM Element.

Creating a DOM element variable

A DOM element variable has two options for the selection method: ID or CSS Selector. The one we are interested in is the CSS selector option since our HTML tag does not have an ID attribute.

Select CSS Selector for the selection method, then paste the CSS Selector we used inside the querySelector command.

CSS selector method for the DOM element variable

We can also use the query selector method to create a custom trigger. 

Head over to Triggers New.

Creating a new trigger

We’ll be creating an element visibility trigger. This trigger fires when a selected element becomes visible in the web browser’s viewport. 

Click on Trigger ConfigurationElement Visibility.

Creating an element visibility trigger

Like the DOM element variable, we’ll select CSS Selector for the selection method, and then paste the CSS Selector we used inside the querySelector command.

CSS Selector method for the element visibility trigger

Under advanced settings, we can also use the CSS selector method, so that the trigger will fire only on Some Visibility Elements. Here, you can make the trigger fire when a certain variable matches CSS selector with the page element we picked.

Matches CSS selector advanced settings

💡 Top Tip: Always test your CSS selectors before using them in your variables, triggers, or tags. Use the query selector method inside your browser’s developer tools to ensure that it returns your desired results

4. Google Tag Manager Object

Next up, we have the Google Tag Manager object.

This is especially useful when you are looking again at the Data Layer. The dataLayer command we utilized earlier gives you access to the Data Layer, but not the internal model of Google Tag Manager. This is an object on the page itself.

Google Tag Manager has an internal representation of the Data Layer that can be different from the tags and variables we define.

GTM internal representation of data

When you want to access the internal data model of Google Tag Manager, you will first need to know your GTM container ID, which you can locate at the top of your GTM homepage.

GTM container ID

The command syntax we will use to invoke the GTM object command is:


When you type out the command in the console tab of your browser’s developer tools, your container ID can also pop up as a suggestion.

GTM container ID automatically detected and shows as a suggestion

💡 Top Tip: Press the right arrow key to autofill your container ID without typing it or selecting it from the list.

The things you can do with the GTM object command are multifold, but what we have found is especially useful for looking at the Data Layer. 

We can then use the get command to fill in anything that we would usually put into our Data Layer variable. What you usually put inside the data layer variable name can also be used inside the GTM object.

To illustrate how you can pull data from the Data Layer using the GTM object command, let’s go into the Tag Assistant → Data Layer and see what kind of elements we have. 

For this example, let’s look at the ecommerce.currencyCode.

ecommerce.currencyCode in the Data Layer

We would normally build a Data Layer variable out of this and go into the Tag Assistant and check if it’s working properly there. However, with the GTM object command, we can easily test it out without building the variable.

The command syntax should now be:


Type this in the console tab, then press Enter. It should then return the corresponding value for our key as what was written in the internal data model.

GTM object command pulling data from the Data Layer