Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
Passing a dynamically created variable to another function (Vanilla Javascript)

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" class="test">Test</button>
    <button id="update">Update</button>
    <section id="textArea">
    </section>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!