Don't have one? Create one ↗
← All courses

Lesson 8 of 15

Scrape Data From The DOM

① Connect your GTM container

Paste your container ID to load it into this page. It only ever runs here.

Advanced: use a specific environment

Not every value you want is in the dataLayer. Sometimes the only place a product's name, price or SKU exists is the rendered HTML on the page. When you cannot get a developer to push it, you read it straight from the markup with a DOM Element variable.

A DOM Element variable points at an element (by ID or CSS selector) and returns either its text or one of its attributes. Here the button below pushes a bare add_to_cart with no product data, so you will scrape the details yourself and attach them to your tag.

Goal

Read the product name, price, SKU and rating from the page markup with DOM Element variables.

Build it in GTM

  1. Read the product name from element text

    Go to Variables → New and choose DOM Element.

    1. Set Selection Method to ID and Element ID to product-name.
    2. Leave Attribute Name empty so it returns the element's text. Name it DOM - product name and Save.
  2. Read the price from a data attribute

    Another DOM Element variable, Selection Method ID, Element ID product-price, but this time set Attribute Name to data-price so it returns 129.00 rather than the formatted $129.00 text.
  3. Read the SKU and rating by CSS selector

    For these, set Selection Method to CSS Selector. Use [data-sku] with Attribute Name data-sku, and [data-rating] with Attribute Name data-rating. (A single Custom JavaScript variable using document.querySelector is an accepted alternative.)
  4. Attach the values to a tag

    On a tag firing on the add_to_cart event, send your four scraped variables as parameters. Use a Custom HTML tag named Custom HTML - Test containing <script></script> as a stand-in; on the real site this is a GA4 Event tag mapping item_id, item_name and price.

Debug in Tag Assistant

Copy this lesson's live URL and paste it into GTM Preview, that is the page Tag Assistant connects to. It has the clickable elements, so this page stays clean for reading.

  1. In your GTM, click Preview.
  2. Paste the live URL above and click Connect.
  3. Interact with the live page and watch your tag fire in Tag Assistant.

What you should expect to see

Open Tag Assistant's Variables tab while on this page: {{DOM - product name}} resolves to Aurora Wireless Headphones, the price variable to 129.00, and the SKU and rating to AUR-WH-09 and 4.6, values that exist only in the markup.

Verify your container

Built it? Export your container, Admin → Export Container, choose your workspace, then drop the JSON here to check it against this lesson.

Drop your container .json here

or browse · checked in your browser, nothing is uploaded

0 of 15 lessons complete