When retrieving the data-attribute on a HTML element I have run into a problem using jQuery.
I wish to manipulate the attributes and some elements have more data-attributes than others.
Using jquery-1.10.1.js when converting to JSON it works fine, i.e. the order as they appear on the HTML element.
(data-id, data-col, data-sport + any additional data)
If I replace jQuery version jquery-1.10.2 to a later version starting with, jquery-1.11.0 it does the opposite and has the last data-attribute first. (in the code snippet is the older version of jQuery showing how it should look).
$(document).ready(function(){
$(".btnOne").on('click', function(){
a = $(this).data();
b = JSON.stringify(a)
var count=Object.keys(a).length;
console.log("a: "+b+" -- "+Object.keys(a));
console.log("KEY: --- "+Object.keys(a)[2]);
if(a[Object.keys(a)[2]]=="Golf"){
console.log("CHANGE");
a[Object.keys(a)[2]] = "Snooker";
$(this).html(a[Object.keys(a)[2]]);
};
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<p class="btnOne" data-id="14" data-col="R" data-sport="Rugby">Rugby</p>
<p class="btnOne" data-id="12" data-col="B" data-sport="Cricket" data-team="Somerset" >Cricket</p>
<p class="btnOne" data-id="23" data-col="Y" data-sport="Golf">Golf</p>
Object.keys(a)[2]to be "sport", just usea.sport.