Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

146
Visualizações
Toggle Two Divs Onclick JavaScript

I am writing a function that toggles two divs onclick. I have 2 functions that displays an api json data as a table and graph (formatGraph and formatTable). i have created two different divs and appended the formatGraph and formatTable functions to those divs. Then created a mainDiv to wrap the two divs.

I have an if statement that checks for when to show or hide the divs. I am calling the formatData function somewhere in my fetch call while rendering my result. I have a css file with the following code:

.displayTable {
    display: block;
}

.displayGraph{
    display: none;
}

But I am currently getting undefined and

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

Any idea what I am missing, or how I can go about this? Here's my function:

const formatData = (response) => {
    const mainDiv = document.createElement("div");
    const div1= document.createElement("div");
    div1.classList.add("displayTable");
    div1.appendChild(formatTable(response));
    mainDiv.appendChild(div1)

    const div2 = document.createElement("div");
    div2.classList.add("displayGraph");
    div2.appendChild(formatGraph(response));
    mainDiv.appendChild(div2)
    

    viewTable.addEventListener("click", function() {

    if(document.querySelector('.displayTable').style.display === "none") {
        document.querySelector('.displayGraph').style.display = 'none';
        document.querySelector('.displayTable').style.display = 'block';
    }

    else{
        document.querySelector('.displayTable').style.display === "none"
       document.querySelector('.displayGraph').style.display = 'block';
    }
    
    
})
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

your code looks OK, but you're forgetting to append mainDiv to the document. That's why you're getting null as a result of calling document.querySelector(".displayTable") and document.querySelector(".displayGraph"). Using the access operator in null results in a TypeError.

//...
const div2 = document.createElement("div");
div2.classList.add("displayGraph");
div2.appendChild(formatGraph(response));
mainDiv.appendChild(div2)
document.body.appendChild(mainDiv);
//...

I've just used .appendChild in body, which appends the element at the end of the body. There are different methods that let you append elements at different locations of the DOM three. You could also create an empty element (has no children) in your HTML and use that element as a wrapper to append the DIVS.

Also, consider an improvement in your handler:

viewTable.addEventListener("click", function() {
  // Execute document.querySelector once.
  const displayTableDiv = document.querySelector('.displayTable')
  const displayGraphDiv = document.querySelector('.displayGraph')
  
  /* This new condition will prevent the Type Error if any. */
  if (displayTableDiv && displayGraphDiv) {
    if(displayTableDiv.style.display === "none") {
      displayGraphDiv.style.display = 'none';
      displayTableDiv.style.display = 'block';
    }
    else {
      displayTableDiv.style.display === "none"
      displayGraphDiv.style.display = 'block';
    }
  }
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda