Toggle boolean attributes in DOM elements

function toggleAttrs(attributes, elements) { if (Array.isArray(attributes)) { attributes.forEach(function(attribute) { if (typeof elements === 'string') { elements[attribute] = !elements[attribute]; } else if (Array.isArray(elements)) { elements.forEach(function(element) { element[attribute] = !element[attribute]; }); // End of element array iteration } // End of type checking }); // End of attribute array iteration } else if (typeof attributes === 'string') { if (typeof elements === 'string') { elements[attributes] = !elements[attributes]; } else if (Array.isArray(elements)) { elements.forEach(function(element) { element[attributes] = !element[attributes]; }); // End of element array iteration } // End of type checking } // End of type checking } // End of toggling boolean attributes // This function toggles DOM element attributes that are, // redundatly speaking toggleable because they're boolean. // Here's an example case using "disabled: boolean" in a button. var btn = document.getElementById("start-button"); toggleAttrs("disabled", btn); // Button is now disabled if previously enabled or visceversa. // You can also toggle multiple attributes and elements at once // By passing an array of elements and/or boolean attributes.
Toggle boolean attribute in HTML elements such as "disabled". Currently working on a version that replaces the forEach approach with simple FOR loops in order to be able to pass live node arrays that can't be iterated over with forEach or any other functional programming array method. ─ This snippet is a piece of a JavaScript library I'm working on, you can see it here:

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.