skip to Main Content

Im new to coding and Im trying to make a "page not found" page but im getting the following error

Uncaught TypeError: Cannot read properties of undefined (reading 'add')

How can I solve this problem?

Here is the code:

  setTimeout(function () {
    const notFoundElement = document.getElementsByClassName(
      "not-found-animation"
    );
    notFoundElement.classNameList.add("hinge-falling");

    console.log("setTimeout Loaded...");
  }, 2200);
<h1 className="not-found-animation">404</h1>

4

Answers


  1. you need to access the first element in the collection using [0],
    Try:

     setTimeout(function () {
          const notFoundElement = document.getElementsByClassName(
            "not-found-animation"
          );
          notFoundElement[0].classList.add("hinge-falling");
        
          console.log("setTimeout Loaded...");
        }, 2200);
    
    Login or Signup to reply.
  2. did you by any chance mean classList.add? although i cant rly see how is that react related

    Login or Signup to reply.
  3. try this notFoundElement.setAttribute(‘class’,’hinge-falling’)

    Login or Signup to reply.
  4. Don’t use the original DOM in React (bad practice).

    solutions

    • Using useState Hook
    const [toggle, setToggle] = useState(false);
    setTimeout(function () {
      setToggle(!toggle);
    
      console.log("setTimeout Loaded...");
    }, 2200);
    <h1 className={`${toggle && "not-found-animation"}`}>404</h1>;
    
    • Using useRef Hook
    const ref = useRef(null);
    setTimeout(function () {
      const h1 = ref.current; // corresponding DOM node
      h1.className = "not-found-animation";
      console.log("setTimeout Loaded...");
    }, 2200);
    
    <h1 ref={ref}>404</h1>;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search