0

I am trying to call the below through in Google Tag Manager:

document.getElementById('Travel_J608883332').innerText

An issue I have is that the ID changes with each booking i.e. the J608883332 is dynamic to the booking number.

I have read about using the querySelectorAll method to create a Regex pattern that might pull back the element dynamically:

return document.querySelectorAll('span[id="^TravelBy\_J.*"]').innertext

However the above is returning "undefined" when I test in Google Tag Manager. I assume I have made an error in constructing it?

Apologies for the naive question, I am new to this method.

Thanks, M

user3411489
  • 17
  • 1
  • 5
  • Possible duplicate of [Can I use a regular expression in querySelectorAll?](https://stackoverflow.com/questions/16791527/can-i-use-a-regular-expression-in-queryselectorall) – Johan Karlsson Feb 01 '19 at 12:40

2 Answers2

1

You can use with a prefix attribute selector. In addition, the collection returned by document.querySelectorAll() doesn't have an innerText attribute. In this example, I've converted the collection to an array, and extract an the texts by mapping the items. If you only have a single element each time, use document.querySelector(), and then you can extract the inner text directly.

const text = Array.from(document.querySelectorAll('span[id^="TravelBy_"]'))
  .map(el => el.innerText);

console.log(text);
<span id="TravelBy_123">123</span>
<span id="TravelBy_456">456</span>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

querySelectorAll returns a NodeList and innerText is not an attribute of NodeList. Other point is querySelectorAll does not support regular expression but you can use CSS selector instead:

var queryResult = document.querySelectorAll('span[id^="Travel"]');
console.log(queryResult.innerText); // >>> undefined
console.log(queryResult != null && queryResult.length > 0 ? queryResult[0].innerText : '-');
Marcelo Vismari
  • 1,147
  • 7
  • 15