jquery

how to toggle attr() in jquery


I have a simple add attribute function:

$(".list-toggle").click(function() {
    $(".list-sort").attr('colspan', 6);
});

My question is: how can I turn this into a toggle, so colspan="6" is removed from the element on the next click?


Solution

  • If you're feeling fancy:

    $('.list-sort').attr('colspan', function(index, attr){
        return attr == 6 ? null : 6;
    });
    

    Working Fiddle

    ES6 Syntax (2021):

    $('.list-sort').attr('colspan', (_, attr) => (attr == 6 ? null : 6));