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

124
Views
Use text from DOM element as JSON object with JavaScript

I have a div in my webpage that contains some valid JSON string. I get its value using the text() function in jQuery like this:

$("div.selector").text();

The JSON string contains some new lines and tabs. It is perfectly valid and matches the formatting expected by Google Tag Manager Enhanced eCommerce (https://developers.google.com/tag-manager/enhanced-ecommerce).

The problem I am facing is that using the following prevents the event from being registered

dataLayer.push($("div.selector").text());

while pasting the JSON inside push() manually registers the event properly:

dataLayer.push(VALID JSON);

Using

dataLayer.push($("div.selector").text());

pushes a text string in dataLayer that looks like this

{\n\t\t\"event\": \"someEvent\",\n\t\t\"eventCategory\": \"Order Update\"

How can I push valid JSON that has been extracted using text()?

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

0

Use JSON.parse()

eg: dataLayer.push(JSON.parse($("div.selector").text()));

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!