Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
Grab multiple elements with the same class name using a JS Variable in GTM

I want to grab all of these elements with a GTM variable so that I could send all the product names to Google Analytics whenever a person enters this section of the site.

Inspect Element

I've tried using the DOM element variable, a JS variable with document.getElementByClassName and document.querySelector and querySelectorAll, however all of these return the value of null. I am not that experienced with JS, what am I doing wrong?

Thanks in advance :^)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Edit:

I made a clone from your picture. You can see there are 3 items on the page.
I use grabNames` function to return an array of these 3 items' names.

So, you can copy grabNames function to your GTM custom javascript page.

function grabName() {
  var elems = document.querySelectorAll('.name');  // return elements class = name
  var prodctList = [];  // make a new array
  for (let i = 0; i < elems.length; i ++) // loop entire elems and push each elem name to the list
    prodctList.push(elems[i].innerText); 
  return prodctList; // return array
}

var arr = grabName();
console.log(arr)
.details {
  margin-bottom: 15px;
  padding: 5px;
  border: 1px solid black;
}
<div class="details">
  <div class="summary">
    <div class="summary__item">
      <a class="name">
        prodct name 1
      </a>
    </div>
  </div>
</div>
<div class="details">
  <div class="summary">
    <div class="summary__item">
      <a class="name">
        prodct name 2
      </a>
    </div>
  </div>
</div>
<div class="details">
  <div class="summary">
    <div class="summary__item">
      <a class="name">
        prodct name 3
      </a>
    </div>
  </div>
</div>


I'm not sure how you wrote your code. any error message?

I think the code below should works

document.getElementByClassName('name');

// or

document.querySelectorAll('.name');

You can see these post:

  1. Document.getElementsByClassName()
  2. Document.querySelectorAll()
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!