I am stuck in a concept of html5 data attributes. That attributes allows nesting like:
<div data-user--name="John" data-user--surname="Doe"></div>
I have seen plugins in the past (like select2) and some of them use the following similar syntax to make an AJAX call:
<div data-ajax--url="my/url" data-ajax--method="POST">
This code in background converts to a dataset in javascript and it returns something like this:
data = {
ajax: {
url: "my/url",
method: "POST"
}
}
But in the practice, vanilla javascript's dataset
and jQuery data()
methods return different object content.
Javascript
var el = document.getElementsByTagName("div")[0];
el.innerHTML = "<pre>"+JSON.stringify(el.dataset)+"</pre>";
<div data-ajax--url="my/url" data-ajax--method="POST"></div>
jQuery 1.x
$('div').html("<pre>"+JSON.stringify($('div').data())+"</pre>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-ajax--url="my/url" data-ajax--method="POST"></div>
jQuery 2.x
$('div').html("<pre>"+JSON.stringify($('div').data())+"</pre>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-ajax--url="my/url" data-ajax--method="POST"></div>
The code in error seems to be the jQuery 1.x versions, because in 2.x versions jQuery returns the same as vanilla Javascript. I found a related bug so it's confirmed: https://github.com/select2/select2/issues/2969
But I can't find where to construct a nested javascript object with the nested html syntax, like the following example:
{
ajax: {
url: "my/url"
method: "POST"
}
}
Is there any Javascript method, or a polyfill, that makes this kind of objects reading the data-*
HTML attributes? Is it possible to parse the data javascript strings (i.e. ajax-Method
) and return a nested object (ajax.method
) ?
Ran into exact same need, but @artofcode's answer parses only 2 levels. So I had to figure out how to parse unlimited number of levels. Here's my solution without limiting levels, based on original answer.
Didn't test it thoroughly, but it works in my case, like:
data-buttons--btn1--title
;data-buttons--btn1--icon
;data-buttons--btn2--title
.