The error occurs because TypeScript doesn't recognize the style property on a generic Element. To fix this, we need to explicitly type the SVG element. Here's the corrected code:
<script>
document.addEventListener("DOMContentLoaded", () => {
const accordionButtons = document.querySelectorAll(".faq-item button");
accordionButtons.forEach((button) => {
const controlId = button.getAttribute("aria-controls");
const content = controlId ? document.getElementById(controlId) : null;
button.addEventListener("click", () => {
const expanded = button.getAttribute("aria-expanded") === "true";
button.setAttribute("aria-expanded", (!expanded).toString());
if (content) {
content.classList.toggle("hidden");
}
// Cast to SVGElement to access style property
const icon = button.querySelector<SVGSVGElement>(".faq-icon");
if (icon) {
icon.style.transform = expanded ? "" : "rotate(180deg)";
}
});
});
});
</script>
Key changes:
- Added type assertion
<SVGSVGElement> to querySelector
- Ensured TypeScript recognizes the SVG element's properties
Alternative solution using class toggling (avoids style manipulation):
<script>
document.addEventListener("DOMContentLoaded", () => {
const accordionButtons = document.querySelectorAll(".faq-item button");
accordionButtons.forEach((button) => {
const controlId = button.getAttribute("aria-controls");
const content = controlId ? document.getElementById(controlId) : null;
button.addEventListener("click", () => {
const expanded = button.getAttribute("aria-expanded") === "true";
button.setAttribute("aria-expanded", (!expanded).toString());
if (content) {
content.classList.toggle("hidden");
}
const icon = button.querySelector(".faq-icon");
if (icon) {
icon.classList.toggle("rotate-180");
}
});
});
});
</script>
<style>
.faq-icon {
transition: transform 0.2s;
}
.rotate-180 {
transform: rotate(180deg);
}
</style>
Both solutions fix the TypeScript error while maintaining the same functionality. The first solution uses direct DOM manipulation with proper typing, while the second uses CSS classes for better separation of concerns.