I am facing an issue where certain elements need to be highlighted or unhighlighted conditionally. To achieve this, I have assigned a class called highlight
to the elements that require highlighting with a transition animation.
The challenge arises when trying to animate the removal of the highlight
class from elements. Since any element could potentially be highlighted, it is difficult to find a specific selector for them.
One workaround could be applying the transition property to all elements, but this solution does not feel optimal:
* {
transition: background-color 1s;
}
Is there a more efficient way to address this issue? Below is a simplified example illustrating the problem:
[...document.querySelectorAll('body *')].forEach(e => e.addEventListener('click', () => e.classList.toggle('highlight')));
.highlight {
background-color: red;
transition: background-color 1s;
}
<h2>Click anything to toggle highlight</h2>
<p>Hello</p>
<p>World</p>
<p>Thanks</p>