jQuery: missing method toggleAttr for toggling attributes

Today I needed some JS-Code for toggling an DOM elements attribute. Because there is no such feature in the
jQuery core, I implemented it. Perhaps it’s useful for you, so here it is :)


jQuery.fn.toggleAttr = function(attribute, value) {
    value = value || attribute;
    return this.each(function() {
        var attr = jQuery(this).attr(attribute);
        if (typeof attr !== typeof undefined && attr !== false) {
        else {
            jQuery(this).attr(attribute, value);

When you do not give a value, it’s assumed that you want to toggle attributes like
disabled or selected, so the value is automatically adjusted the attribute
name. Have a look at the example:


// For example, you have a multiple select control:
// <select multiple="multiple" size="5" id="my-select">
//     <option>Option 1</option>
//     <option>Option 2</option>
//     <option>Option 3</option>
//     <option>Option 4</option>
//     <option>Option 5</option>
// </select>

// You can easly add a "invert selection"-method, which toggles all items
$('#my-select option').toggleAttr('selected', 'selected');

// is the same as (with missing value parameter)
$('#my-select option').toggleAttr('selected');

Leave a Reply

Your email address will not be published. Required fields are marked *

Captcha * Time limit is exhausted. Please reload CAPTCHA.