-1

how do I display my object into a string? I get the error message:

Uncaught TypeError: Cannot read properties of null (reading 'appendChild') at HTMLButtonElement.detailClickHandler

  function detailClickHandler(e) {
    let details = e.target
    // get the relative id
    let hero = details.closest('.card').dataset.id
    console.log(hero)

    // display hero description
    let description = document.createElement('p');
    description.innerHTML = hero
    detailsContainer.appendChild(description)

  }

above in my init function I am calling the html:

//globals
let heroes
let hero
let theData = {}
let detailsContainer
let cardsContainer


function init () {
  cardsContainer = document.querySelector(".cards")
  detailsContainer = document.querySelector(".detail")
Gary
  • 19
  • 4
  • Is it possible that the DOM isn't loaded yet? You should put all your functions inside window.onload – Aashish Peepra Apr 10 '22 at 08:53
  • 1
    The error message says that `detailsContainer` is `null` but you haven't shown us how that variable is defined. – Quentin Apr 10 '22 at 08:53
  • I have tried your guys input thank you very much but I haven't made it work yet, I updated the info – Gary Apr 10 '22 at 09:26
  • https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – Quentin Apr 10 '22 at 21:40

1 Answers1

-1

Your detailsContainer is not set. Try details or details.parentElement. Or do a DOM search for it.

// detailsContainer.innerHTML = '';
details.innerHTML = '';
// or
details.parentElement.innerHTML = '';
// or
document.getElementById('#theElement').innerHTML = ''
Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
  • My focus is a little lower, I have changed some details and hopefully it helps drawing a picture with my problem. – Gary Apr 10 '22 at 09:19
  • So `document.querySelector(".detail")` is not finding your element. You need to show use your DOM elements. – Steven Spungin Apr 10 '22 at 15:34