JavaScript: Getting data attributes by class name

From The Travis van der Font Wiki
Jump to: navigation, search
HTML:
<div id="container1" class="container_example">
    <p class="example_class_name" data-info-id="21" data-info-slug="purple-apples" data-info-name="Purple Apples">P.P.</p>
    <p class="example_class_name" data-info-id="42" data-info-slug="red-bananas"   data-info-name="Red Bananas">R.B</p>
    <p class="example_class_name" data-info-id="64" data-info-slug="green-oranges" data-info-name="Green Oranges">G.O.</p>
<div>
Source Code (JavaScript):
var array = [];
var data  = document.querySelectorAll('.example_class_name');

// display all that elements through a NodeList
// console.log(data);

data.forEach(function (element)
{
    array.push(
    {
        id:   element.dataset.infoSlug,
        slug: element.dataset.infoSlug,
        name: element.dataset.infoName
    });
});

console.log(array);