I have written a small JS function to change the class name of an HTML element. Sadly, my const is somehow undefined, so the function doesn't run.
This is my JS:
deglitcher();
function deglitcher() {
const glitch = document.querySelector('#bottom-gl');
setTimeout(function () {
glitch.className = 'glitch-off';
}, 2000);
}
This is how my HTML looks like:
<div >
<h1 id="upper-gl" data-text="Glitch1">Glitch1</h1>
<h1 id="bottom-gl"data-text="Glitch2">Glitch2</h1>
<span >Test</span>
</div>
I would like it to look like that:
<div >
<h1 id="upper-gl" data-text="Glitch1">Glitch1</h1>
<h1 id="bottom-gl"data-text="Glitch2">Glitch2</h1>
<span >Test</span>
</div>
I hope someone smarter than myself, can figure it out
CodePudding user response:
The fix which I came up with, thanks to the generous help of ARMAAN and A Haworth, is as follows:
- Correct the code for bad selector ('bottom-gl) instead of ('#bottom-gl')
- Use classList instead of className
deglitcher();
function deglitcher() {
const glitch = document.getElementById('bottom-gl');
setTimeout(function () {
console.log(glitch)
glitch.classList.add('glitch-off');
glitch.classList.remove('glitch');
console.log('Trele Morele');
}, 2000);
}
- And finally - thanks to A Haworth, I used defer in my loader:
<script src="../src/js/glitch.js" defer></script>
As of now the issue is resolved, thanks for your help everyone ;-)
CodePudding user response:
if the const isn't working then just console.log the variable name,but i did it and it is working.
when you're changing the class I recommend using
classList.add('class-name')//for adding
classList.remove('class-name')//for removing
here you can do it like this
deglitcher();
function deglitcher() {
const glitch = document.querySelector("#bottom-gl");
setTimeout(function () {
glitch.classList.add('glitch-off');//adding the new class
glitch.classList.remove('glitch');//removing the initial class
console.log('Testing if working')
}, 2000);
}
thanks.