Search code examples
jqueryhtmldomunobtrusive-javascriptcustom-data-attribute

get data- attributes values without pass HTML element id


I have INPUT HTML tag with type as hidden in view.It looks as follows:

     <input type="hidden" data-abc-value1="value1" data-abc-value2="value2" data-abc-
         value3="value3"/>

I would like to get the values of data- attributes(data-abc-value1,data-abc-value2,data-abc-value3) without passing element id to it.

Can i somehow find matching data-abc(which is common) attributes for the element and get its values.So that i can avoid dependency on element id to get data -* value.


Solution

  • Try this code, this may help you

    HTML

    <input type="hidden" data-abc-value1="value1" data-abc-value2="value2" data-abc-value3="value3" />
    

    Script

    $('input[type="hidden"]').each(function(i, e){
        $.each(e.attributes, function(j,v){
            if(/^data-abc/.test(v.nodeName)) {
                console.log(v.nodeName, v.nodeValue);
            }
        });
    });
    

    Demo JS http://jsfiddle.net/UYNsw/