Solution
Instead of using querySelector
to select a single element by its ID, we can utilize querySelectorAll
to target multiple elements based on a class name. IDs should be unique, so it's better to use classes when selecting multiple elements.
// Select all elements with the text-container class
const containers = document.querySelectorAll(".text-container");
for (let i=0; i<containers.length; i++) {
// For each container, find the span element for animation
const text = containers[i].querySelector("span");
if (containers[i].clientWidth < text.clientWidth) {
text.classList.add("animate");
}
}
Instead of a traditional for loop, you could also use a forEach
method which some find easier to read and maintain. Use whichever method you feel most comfortable with!
// Select all elements with the text-container class
const containers = document.querySelectorAll(".text-container");
containers.forEach((container) => {
// For each container, find the span element for animation
const text = container.querySelector("span");
if(container.clientWidth < text.clientWidth) {
text.classList.add("animate");
}
})
}
Recommendation
I suggest adding a specific class to those 16 elements to avoid accidental reuse. Using a generic name like .text-container
is preferable over something more specific like .js-animated-card
.
Prefixing your JS-related classes with js-
can help differentiate them from purely styling classes. This makes it easier to manage and modify your styles without affecting your JavaScript functionality.