Looping through object and add data attributes to HTML elements

Hi,

I’m trying to loop through an object which includes the CSS class/element name which I want to target on the page, and then the child object of that is the data attribute property and value which I want to add onto the CSS class/element.

I’m able to do the looping part, however getting the values to then add as data attributes onto the HTML elements is the bit I’m struggling with. Code below. Due to how the site’s build, I can’t add the data attributes onto the HTML elements manually, so have to do it with JavaScript.

// Uses parsley.js var formConfig = { '.web-form': { 'data-prasley-validate': '' }, 'input[type="email"]': { 'data-parsley-required': 'true', 'data-parsley-type': 'email' } };

$.each(formConfig, function(index) {
$.each(formConfig[index], function(key, value) {
$(index).attr({
key : value
});
});
});

Hi,

What might be easier is if you post a snippet of the HTML you currently have, then a second snippet of what you would like the HTML to look like once you have added the data attributes to it.

Agreed.

Also, watch out for typos. “prasley” != “parsley”

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.