Lesson 7 of 8
DOM Scraping, Safely
When the data lives only in the markup, you read it with the DOM. The trick is doing it without throwing errors when the page differs from what you expected.
// Custom JS variable: read a price from the page
function () {
var el = document.querySelector('[data-price]');
if (!el) return undefined; // guard: element may be missing
var raw = el.getAttribute('data-price') || el.textContent || '';
var num = Number(raw.replace(/[^0-9.]/g, ''));
return isNaN(num) ? undefined : num; // guard: bad value
}Selectors, briefly
querySelector('.class')returns the first match;querySelectorAllreturns all.- Prefer stable hooks (
[data-price], an id) over fragile, deeply-nested CSS paths that break on redesign.
Why scraping is a last resort
DOM scraping works, but it is brittle: a layout change can silently break it. Use it to ship today, then request a proper dataLayer push as the durable fix.
Key takeaway
Scrape with stable selectors and always guard against missing elements and bad values. Treat it as a fast patch, and push for a real dataLayer value as the permanent fix.