To create a functional accordion using JavaScript without the need for any CSS styling or advanced HTML structures, you mostly need to focus on the JavaScript logic that handles the click events and toggles the visibility of content sections. Let's simplify it to focus on just making it function properly.
Here's a basic setup with only JavaScript handling:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Accordion Functionality</title>
</head>
<body>
<div id="accordion">
<div class="accordion-section">
<button class="accordion-header">Section 1</button>
<div class="accordion-content">Content for section 1.</div>
</div>
<div class="accordion-section">
<button class="accordion-header">Section 2</button>
<div class="accordion-content">Content for section 2.</div>
</div>
<div class="accordion-section">
<button class="accordion-header">Section 3</button>
<div class="accordion-content">Content for section 3.</div>
</div>
</div>
<script>
// JavaScript will go here
</script>
</body>
</html>
JavaScript
Here's a JavaScript snippet to handle the accordion functionality without focusing on any specific styling requirements:
<script>
// Select all accordion headers
const headers = document.querySelectorAll('.accordion-header');
// Attach click event to each header
for (let i = 0; i < headers.length; i++) {
headers[i].addEventListener('click', function () {
// Toggle visibility of the associated content
const content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
</script>
Key Features of the Script:
-
Query Selection: All elements with the class accordion-header (the buttons) are selected and stored in the headers variable.
-
Event Listener Setup: A loop iterates through each header button and attaches a click event listener.
-
Visibility Toggle:
- The
nextElementSibling property is used to access the corresponding content div next to each button.
- Toggles the
display property between "none" and "block" to show or hide the content upon each click.
This code should give you a functional accordion without relying on CSS or advanced HTML semantics. You simply click on the buttons to toggle the visibility of the content sections beneath them.