Home > Blockchain >  Why can't I remove this class with javascript?
Why can't I remove this class with javascript?

Time:04-01

I'm trying to make a skeleton loading screen by having a class 'skeleton' on the elements which styles them then removing it with javascript after a timeout. The issue is that i can't get the javascript to work.

Here's my javascript to remove the class, why isn't it working?

const timeout = setTimeout(loading, 3000);

function loading() {
    const element = document.getElementById("skeleton");
    element.classList.remove("skeleton");   
  }

CodePudding user response:

What I think is happening is that you have too many "skeleton" elements with the same id, and ids have to be unique. So remove the ids, and target the classes instead, and use forEach to iterate over each of them to remove the class.

const timeout = setTimeout(loading, 3000);

function loading() {
  const skeletons = document.querySelectorAll('.skeleton');
  skeletons.forEach(skeleton => {
    skeleton.classList.remove('skeleton');
  });   
}
.skeleton { color: red; }
<div >One</div>
<div >Two</div>
<div >Three</div>
<div >Four</div>

CodePudding user response:

You are calling getElmentById on Class. Can You Share The HTML Elment whose id or class is skeleton try this


function loading() {
    const element = document.getElementsByClassName("skeleton")[0];
    element.classList.remove("skeleton");   
  }

CodePudding user response:

I think the reason behind its not working is that your trying to remove the skeleton class from the skeleton itself. Try targeting the parent Element of the skeleton and then remove the skeleton from the parent Element. Did you try using :

const parentNode=document.querySelector(".parentElem");
parentNode.removeChild(document.querySelector(".skeleton"));

Did you notice you are trying to get an element by using getElementById whereas you stated skeleton is a class.

  • Related