I am looking to create a simple accordion within my chrome ext to display data. I am using the following JS tutorial but I seem to be struggling to register a click.
I have returned some data using the following:
//background.js
...
// Looping through object's key value pair to place into divs
for (const [key, value] of Object.entries(params)) {
queryParams += `
<div class="text-sm my-1">
<span class="font-bold uppercase mr-1">${key}: </span><span class="font-normal font-mono capitalizev c-word-wrap">${value}</span>
</div>
`;
}
return (completeData += `
<div class="element my-3">
<div class="question flex justify-between pl-6 pr-12 py-4 bg-purple-500">
<span class="text-base text-white font-bold">${pixelType}</span>
<button id="btn">
<i class="fas fa-plus-circle"></i>
</button>
</div>
<div class="answer hideText">
<span id="pixel-url" class="c-word-wrap text-sm font-mono">${pixelUrl}</span>
<span id="query-params">${queryParams}</span>
</div>
</div>
`);
};
...
I then have my logic in a separate file
//accordion.js
const elements = document.querySelectorAll('.element');
elements.forEach((element) => {
let btn = element.querySelector('.question button');
let icon = element.querySelector('.question button i');
var answer = element.lastElementChild;
var answers = document.querySelectorAll('.element .answer');
btn.addEventListener('click', () => {
console.log('btn clicked');
answers.forEach((ans) => {
let ansIcon = ans.parentElement.querySelector('button i');
if (answer !== ans) {
ans.classList.add('hideText');
ansIcon.className = 'fas fa-plus-circle';
}
});
answer.classList.toggle('hideText');
icon.className === 'fas fa-plus-circle'
? (icon.className = 'fas fa-minus-circle')
: (icon.className = 'fas fa-plus-circle');
});
});
I have also tried to place the same logic in popup.js
which didn’t work either. I am loading my scrips in like so…
popup.html
<!-- Scripts -->
<script src="popup.js"></script>
<script src="../background.js"></script>
<!-- Accordion -->
<script src="../fa.js"></script>
<script src="../accordion.js"></script>
If anyone can guide me in where I am going wrong here that would be great. I have also tried replicating the tutorial outside of a chrome ext and it works perfectly