[英]querySelectorAll for dyanmic span id
I am trying to call the below through in Google Tag Manager: 我正在尝试通过Google跟踪代码管理器致电以下内容:
document.getElementById('Travel_J608883332').innerText
An issue I have is that the ID changes with each booking ie the J608883332
is dynamic to the booking number. 我遇到的一个问题是,每次预订时ID都会更改,即J608883332
对预订号是动态的。
I have read about using the querySelectorAll method to create a Regex pattern that might pull back the element dynamically: 我已阅读有关使用querySelectorAll方法创建可动态回退元素的Regex模式的信息:
return document.querySelectorAll('span[id="^TravelBy\\_J.*"]').innertext
However the above is returning "undefined" when I test in Google Tag Manager. 但是,当我在Google跟踪代码管理器中进行测试时,以上代码返回“ undefined”。 I assume I have made an error in constructing it? 我认为我在构造它时犯了一个错误?
Apologies for the naive question, I am new to this method. 对于天真问题,我很抱歉,我是这种方法的新手。
Thanks, M 谢谢,M
You can use with a prefix attribute selector . 您可以将其与前缀属性选择器一起使用 。 In addition, the collection returned by document.querySelectorAll()
doesn't have an innerText
attribute. 此外,由document.querySelectorAll()
返回的集合不具有innerText
属性。 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. 如果每次只有一个元素,请使用document.querySelector()
,然后可以直接提取内部文本。
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>
querySelectorAll returns a NodeList and innerText is not an attribute of NodeList. querySelectorAll返回一个NodeList,而innerText不是NodeList的属性。 Other point is querySelectorAll does not support regular expression but you can use CSS selector instead: 另一点是querySelectorAll不支持正则表达式,但是您可以使用CSS选择器:
var queryResult = document.querySelectorAll('span[id^="Travel"]');
console.log(queryResult.innerText); // >>> undefined
console.log(queryResult != null && queryResult.length > 0 ? queryResult[0].innerText : '-');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.