Home > Enterprise >  Passing a dynamically created variable to another function (Vanilla Javascript)
Passing a dynamically created variable to another function (Vanilla Javascript)

Time:06-13

I have updated my question to include the code. The "updateNewP" function is not updating the innerHTML but it is not throwing an error. Do I need to add "this" somewhere in both of these functions? Javascript:

let initial = document.getElementById("test");
initial.addEventListener("click", newPElement);

let update = document.getElementById("update");
update.addEventListener("click", updateNewP);

let myTextArea = document.getElementById("textArea");

//function that creates a P
function newPElement(){
let newP = document.createElement("p");
newP.classList.add("myFont");
newP.innerHTML = "Initial Text";
myTextArea.appendChild(newP);
return newP;
}

function updateNewP(newP){
    newP.innerHTML ="Updated";
}

HTML:

<h1>Testing</h1>
    <button id="test" >Test</button>
    <button id="update">Update</button>
    <section id="textArea">
    </section>

CodePudding user response:

The newP variable that was declared within functionA is only available in functionA. If you need to work with this variable in a newPUpdate, it needs to be passed as an argument:

function functionA() {
  const newP = document.createElement("div");
  newPUpdate(newP);
}

function newPUpdate(elem) {
  elem.innerHTML = `${someVariable}`;
}

Looking up variable scope in javascript will help you understand what's going on.

CodePudding user response:

The addEventListener passes event to the function. Event does not have the innerHTML key because it is not an element.

  • Related