Search code examples
jquerycsskeyvaluepair

jQuery -get data attributes & assign them as CSS in a key value pair


I have the following HTML

    <h4 data-padding-top="100" data-padding-left="0" data-text-align="left" data-color="#ffffff">Promotion Two</h4>

I want to take the data attributes and assign them back as CSS styles to the H4. I have the following JS code but the css function call gives an error (I don't want to simply add style=""; in the HTML the client isn't comfortable):

    var H4obj = {},
        $thisH4;

    function css(el, styles) {
        console.log(styles);
        for (var property in styles)
            el.style[property] = styles[property];
    }

    $('h4').each(function(index, el) {
        $thisH4 = $(this);

        var el = $thisH4;

        data = $thisH4.data();

        $.each(data, function(key, val){
            H4obj['data-' + key] = val;
        });

        $.each(H4obj, function(index, value){                
            css($thisH4, {index:value});
        });
    }); 

Am I over-killing this, is there a simpler way to do it ?

Any help is much appreciated


Solution

  • You are making a couple of mistakes I think... it looks to me like you have more variables than necessary, and since you're already using jquery, you should use jquery's built-in method .css.

    $('h4').each(function(index, el) {
        var $el = $(el); // the jquery h4 object
    
        var data = $el.data();
        $el.css(data);
    }); 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <h4 data-text-align="left" data-color='red'>Test One</h4>
    
    <h4 data-text-align="right" data-color="blue">Test Two</h4>

    Basically, .css requires a key value pairs with the "data-" trimmed off the keys. This is exactly what .data() gives you. Also make sure you declare all your variables (they may have been declared above the snippet you posted, I can't tell).