Jyoti Duhan Jyoti Duhan - 2 months ago 9
HTML Question

loop over dom element to get attributes value

I have a set of DOM elements and want to loop over this and get the data-attribute values for each of these element nodes.

[
<div class=​"something" data-prod-name=​"a" data-category-name=​"b" data-brand=​"ABC" data-product-id=​"137427">​</div>​,
<div class=​"something" data-prod-name=​"b" data-category-name=​"b" data-brand=​"ABC" data-product-id=​"128830"></div>​,
<div class=​"something" data-prod-name=​"c" data-category-name=​"b" data-brand=​"ABC" data-product-id=​"128827">​</div>​,
<div class=​"something" data-prod-name=​"d" data-category-name=​"b" data-brand=​"ABC" data-product-id=​"128824">​</div>
]


I tried getting the values like
$('.something')[0].attributes()
, but it did not work. Can anyone help me in getting the desired result?

Thanks in advance :)

EditJustification:
My question is different as I wanted a simple solution and the the question marked by @madalin as a solution/possible duplicate was not clear but making the things more complicated to understand. @samir advised me the simplest solution. Thanks @samir.

Answer

Try using like this,

$(document).ready(function() {
    $('.something').each(function(){
       var dataProdName = $(this).attr('data-prod-name');
       alert(dataProdName);
    });
});