Inside the Minds of the Machine

SEO and Content Marketing, Talking Tech


Google Tag Manager (GTM) does not allow you to target deeply nested selectors.

In this example we’ll target all links that are nested within a DIV with the class .main-nav.

In the above HTML block I would ideally target all of the <A> links by using the CSS selector .main-nav a. Unfortunately GTM doesn’t allow you target all of an HTML selector’s nested elements with traditional CSS selectors.

Following GTM conventions, in order to target all of the <A> links in the above HTML we need to test against fairly direct selectors. For example, we could test against these classes:

  • .main-nav-items-wrap li a
  • .otherlinks a

Unfortunately, we need to setup a separate GTM trigger for each class in order to track it. If your element nesting structure is more complex than this example, it could mean that you need to setup many variants of the GTM trigger.

To simplify the GTM setup we can track all of our .main-nav links with just one trigger by using a little jQuery. All you need to do is loop through part of your page’s elements and add a class that we can use for targeting. The following script loops through all of the <A> tags contained within .main-nav and adds the class .gtm-main-nav.

     if ($(".main-nav a")[0]){
	$( ".main-nav a" ).each(function( index ) {

After running this jQuery function the resulting HTML looks like this:

You now have access to a simple CSS class variable that you can test against in GTM. Here are screenshots from Google Tag Manager showing how my Tag and Trigger is configured to track link clicks for all links within the DIV .main-nav.

Google Tag Manager (TAG setup)

TAG setup

Google Tag Manager (TRIGGER setup)