Highlighted

How can I read value set within the HTML data attributes and make it available to Data Object Layer?

Bronze Contributor
Bronze Contributor
If I have a tag like
How can I read the "data-colors" attribute, convert this into a JSON object and make it available in the Data Layer? Thanks
3 REPLIES 3
Highlighted

How can I read value set within the HTML data attributes and make it available to Data Object Layer?

Employee Emeritus
There's no automatic way to do this in the data layer. You would need to use a JavaScript code extension. If you are using jQuery, then this code should work: {code:js} if (window.jQuery) { var colors = jQuery("#colors").data("colors"); for (var color in colors) { if (typeof colors[color] == "string") { b["color-" + color] = colors[color]; } } } {code} This will check for jQuery, and then use it to read the
node from the html. It will then create a data layer variable from each entry. In your example html, it will create two data layer variables: "color-white" and "color-red". You also need to add the variables in the Data Sources config tab, before you can use them in mappings. They will exist in the data layer but the tags won't know about them until you add them to the list.
Highlighted

How can I read value set within the HTML data attributes and make it available to Data Object Layer?

Employee Emeritus
if you're trying to copy all data- attributes from all elements into the data layer you can run a jQuery snippet like this: {code:javascript} data_attr = {}; $("*").filter(function () { var attrs = this.attributes; for (var i = 0; i < attrs.length; i++) { if (attrs[i].nodeName.indexOf('data') === 0) { a = attrs[i].ownerElement; b = attrs[i].ownerElement.parentElement; key = b.localName + "-" + (!b.id ? (!b.className ? i : b.className) : b.id) + "_" + a.localName + "-" + (!a.id ? (!a.className ? i : a.className) : a.id) + "_" + attrs[i].nodeName.replace("data-", ""); window.data_attr[key] = attrs[i].nodeValue; return true; } }; return false; }) $.extend(utag.data, data_attr); {code} This will create (hopefully) unique keys and the values of the data-attribute to an object and merge them with the utag.data UDO. something like below: {code:javascript} Object {html-2_body-com-html5doctor_twttr-rendered: "true", p-tweet_iframe-twitter-widget-0_twttr-rendered: "true", pre-1_span-tag_colors: "test"} {code} the varibale names might be a bit long, but since the data- attribute most likely will be reused in multiple elements I used a combination of element type,id,class, and data attribute to create the keys. Hope this helps.
Highlighted

How can I read value set within the HTML data attributes and make it available to Data Object Layer?

Not applicable
Hi there I have a similar need but it is a span class IN STOCK I just want jquery to check for the presence of this class ("in stock" is irrelevant) How would you recommend doing that? Thanks!