You can simplify your code by:
-
Eliminating the Array Conversion: Modern browsers support the .forEach method directly on NodeList, so there's no need to convert it to an array using Array.from.
-
Replacing Bitwise XOR Operator: Using button.disabled ^= true can be unclear. Instead, use button.disabled = !button.disabled for better readability and clarity.
-
Combining Steps: Reduce the number of intermediate variables by chaining the operations.
Here's the simplified version of your code:
document.querySelectorAll('.moveSelectedButton').forEach(button => {
const groupIdOfButton = button.parentElement.parentElement.dataset.groupId;
if (groupIdOfButton !== groupId) {
button.disabled = !button.disabled;
button.style.textDecoration = button.disabled ? 'line-through' : 'none';
}
});
Further Improvements
For enhanced readability and maintainability, you can define a helper function or use the closest method if the HTML structure allows it. Additionally, managing styles via CSS classes is generally a better practice than manipulating styles directly in JavaScript.
Using closest and CSS Classes:
-
Define a CSS Class:
.disabled {
text-decoration: line-through;
}
-
Simplify JavaScript:
document.querySelectorAll('.moveSelectedButton').forEach(button => {
const groupIdOfButton = button.closest('[data-group-id]').dataset.groupId;
if (groupIdOfButton !== groupId) {
button.disabled = !button.disabled;
button.classList.toggle('disabled', button.disabled);
}
});
Explanation:
-
closest Method: This method traverses the DOM tree upwards from the current element until it finds a match for the selector. It’s more flexible and readable compared to accessing parentElement.parentElement.
-
CSS Classes: Managing the text-decoration through CSS classes makes your JavaScript cleaner and separates concerns between styling and functionality.
Final Optimized Code
Combining the improvements:
// Define the CSS class in your stylesheet
/*
.disabled {
text-decoration: line-through;
}
*/
document.querySelectorAll('.moveSelectedButton').forEach(button => {
const groupIdOfButton = button.closest('[data-group-id]').dataset.groupId;
if (groupIdOfButton !== groupId) {
button.disabled = !button.disabled;
button.classList.toggle('disabled', button.disabled);
}
});
This approach enhances the readability, maintainability, and scalability of your code.