I have a ul
tag with few li
elements. Each li
have some data attributes.
<ul id="elements">
<li id="mtq" data-id="1" data-name="abc">test 1</li>
<li data-id="2">test 2</li>
<li data-id="3" data-name="xyz">test 3</li>
<li data-id="4" data-name="pqr">test 4</li>
<li data-id="5" data-type="text">test 5</li>
<li data-id="7">test 6</li>
</ul>
I need to get all data attributes (without date-
string) & value of each li
like key:value like below one.
{"id":1,"name":"abc"}
I tried the below javascript code, but I got an error that says Array.prototype.forEach called on null or undefined
.
function getDataAttributes(el) {
var data = {};
[].forEach.call(el.attributes, function(attr) {
if (/^data-/.test(attr.name)) {
var camelCaseName = attr.name.substr(5).replace(/-(.)/g, function ($0, $1) {
return $1.toUpperCase();
});
data[camelCaseName] = attr.value;
}
});
return data;
}
$("#hello").click( function (e) {
$("ul#elements li").each(function() {
var data = getDataAttributes($(this));
console.log(data);
//var json = JSON.stringify(data, null, 2);
//el.appendChild(document.createTextNode(json));
});
});
Here is my jsfiddle. https://jsfiddle.net/a4vya9m4/26/
When I select one li
by ID, it give answer. What is wrong in my script?