Agata
Agata

Reputation: 45

Getting value of ID from class

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")

Upvotes: 0

Views: 576

Answers (3)

Eike Pierstorff
Eike Pierstorff

Reputation: 32770

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

enter image description here

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

Upvotes: 2

Jakub Kriz
Jakub Kriz

Reputation: 1529

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)

Upvotes: 0

Natig Babayev
Natig Babayev

Reputation: 3295

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

Upvotes: 0

Related Questions