DS_web_developer DS_web_developer - 3 months ago 6x
jQuery Question

Get all key/value pairs from data attr that have the same prefix

I am working on a platform and would like to unify and standardize some behaviour throughout the platform...the data- attribute in the html elements will play a huge part...

So lets say I have a button:

<a href="..." class="btn" data-tip="My button" data-modal_tile="Foo" data-templade_data_id="14" data-templade_data_action="reset">...</a>

now, my Javascripts handles the behaviour of this button.

What I would like is to get set a template_data array, that would give me all key/value pairs from the data- attribute that have the same prefix (data-template_data_)...
so in my example I would get:

id: "14",
action : "reset"

What is the best way to do that?


try this

var array = [];
$( ".btn" ).each( function(){
    var obj = {};
    $.each(this.attributes, function() 
        if(this.name.indexOf( "data-templade_data_" ) == 0 ) 
            var key = this.name.replace( "data-templade_data_", "" );
            obj[ key ] = this.value;
    array.push( obj );
} );