Home > Net >  How to style/target a node that is created within a function, from outside of the function
How to style/target a node that is created within a function, from outside of the function

Time:07-21

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');
})

CodePudding user response:

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";

CodePudding user response:

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 >
  container
</div>


<div >
  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.

  • Related