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

203
Visualizações
How to style/target a node that is created within a function, from outside of the function

I want to be able to style (or change) div(s) created within a function. However, this "change" must not be made in the very same function. Given that variables created in functions is in the local scope of that function, how do I reach the created div(s) for later styling (or other changes for that matter) from outside? I have tried targeting the node with querySelector but Console returns Uncaught TypeError since it cannot find the variable.

Example code in JS:

let container = document.querySelector('.container');
let divClass = document.querySelector('.div-class');
divClass.style = "backgroundColor: green";

container.addEventListener('click', () => {
    let createdDiv = document.createElement('div');
    container.appendChild(createdDiv);
    createdDiv.classList.add('div-class');
})
about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

The problem with your code is that you query before the element has even been created.

let container = document.querySelector('.container');
    container.addEventListener('click', () => {
        let createdDiv = document.createElement('div');
        container.appendChild(createdDiv);
        createdDiv.classList.add('div-class');
    })
    
    let someButton= document.querySelector('.someButton');
    someButton.addEventListener('click', () => {
        let divClass = document.querySelector('.div-class');
        divClass.style.backgroundColor = "green";
    })
.container,.someButton{
  border:1px solid black;
  background:grey;
  margin-bottom:4em;
}

.div-class{
  height:40px;
  width:40px;
  border:1px solid red;
}
<div class="container">
  container
</div>


<div class="someButton">
  someButton
</div>

In this snippet, the access to the created div is put in another click event. If you click .someButton before .container it will create an error, but if you click after it will work since the div will be created.

about 4 years ago · Santiago Gelvez Relatório

0

You can make a variable in global scope, and assign it the div which you create later.

const container = document.querySelector('.container');
// assign sample element to avoid error if new_div is used before assigning.
let newDiv = document.createElement('div'); 

container.addEventListener('click', () => {
    let newDiv = document.createElement('div');
    container.appendChild(newDiv);
    newDiv.classList.add('div-class');
})

newDiv.style = "backgroundColor: green";
about 4 years ago · Santiago Gelvez 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