javascriptjqueryjquery-data

How to loop in all data having key names including some text


Assume I have an element like:

<a id="button" data-param1="123" data-param2="456" ... data-paramN="1324" data-anotherName="908678" >Click This</a>

I want to loop in all data having key names including "param" text. For example:

$('a#button').data('param%').each(function(){
   ...
});

Is there anyway to do this?


Solution

  • See the .data() function which automatically decodes data-* attributes and returns them in an object: http://api.jquery.com/data/#data

    Example: http://jsfiddle.net/ET4ER/2/

    $.each( $('a#button').data(), function( key, value ){
        if( key.substr( 0, 5 ) !== 'param') return;
        $('<div>').text( key+'='+ value ).appendTo('body');
    });
    

    Result:

    paramn=1324
    param2=456
    param1=123