0

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>

5
  • 3
    I'm not sure why you'd update a dusty ancient version of jQuery with a very slightly less dusty ancient version. Load v3.x and then make your fixes. Commented Feb 12, 2024 at 21:46
  • 1
    Why does the order of the data- attributes matter? Write your code so that it doesn't matter. I.e., if you expect Object.keys(a)[2] to be "sport", just use a.sport. Commented Feb 12, 2024 at 21:47
  • Also, alerts are a nightmare. Use console logs. Commented Feb 12, 2024 at 21:47
  • 1
    If order is important, use arrays, not objects. See stackoverflow.com/questions/5525795/… Commented Feb 12, 2024 at 21:58
  • 1
    HTML element attribute ordinality can't be guaranteed Commented Feb 12, 2024 at 22:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.