Getting value of ID from class

2019-08-31 05:49发布

问题:

How is it possible to get the value of ID from class using google tag manager?

<html>
    <body>
        <textarea id='5' class='cp _check'>sometexthere</textarea>
    </body>
<html>

Using JQuery it is possible with this:

$(".cp._check").attr("id")

回答1:

Go to variables, select new, type DOM. Select CSS selector. You can then use selectors similarly to jQuery:

Even though there might be multiple matches for your selector GTM retrieves the value for the first occurence only.



回答2:

I guess you should use following code: $("#cp_check").attr("id")



回答3:

Data Uniqueness

This can be unreliable until you cannot be sure that class cp_check is unique.

Data-attribution way

Rather change id from 5 to "form-text-field" (or whatever you want) and your desired value put into data-id:

<textarea id='form-text-field' data-id='5' class='cp _check'>sometexthere</textarea>

And then your jQuery wil looks like:

$("#form-text-field").attr("data-id")

Google Tag Manager

1) Create macro type JavaScript:

function(){
   var dat = $("#form-text-field").attr("data-id");
   return dat;
}

2) Or Create macro type DOM ELEMENT Method -> CSS Selector

  • Selector: .cp_check (in your example) #form-text-field (in this example)
  • Attr: id (in your example) data-id (in thisexample)