简体   繁体   中英

Why did I get an error “Cannot read property 'appendChild' of null”

I have a question for the below code. I get an error:app.js:141 Uncaught TypeError: Cannot read property 'appendChild' of null

const cartDOM = document.querySelector(".cart__center");

    addToCart({ title, price, image, id }) {
        let div = document.createElement('div');
        div.classList.add('cart__item');
    
        div.innerHTML = `<img src=${image} alt="">
        <div>
          <h3>${title}</h3>
          <h3 class="price">$${price}</h3>
        </div>
        <div>
          <span data-id=${id}>`;
    
        cartDOM.appendChild(div);
      }
    }

You are seeing that error because

const cartDOM = document.querySelector(".cart__center");

Is being resolved as null , which means that an element couldn't be found in the document, by using your provided selector ".cart__center" .

This might happen either because:

  • The element doesn't match your selector criteria. Maybe instead of a class name, it's an id, or something else?
  • The element is not in the DOM at the moment to execute that querySelector() , maybe it hasn't been loaded/rendered yet.

Unfortunately there aren't any more details provided about the issue, which would be useful to suggest a solution.

So I can only hope that at least I've provided some useful insight, and I'd suggest you to check the logic of your application to find the best way to fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM