user19716923
user19716923

Reputation:

Why isn't JavaScript displaying the text box value on page

I Want the code to get the number the user has entered and display it on the screen. I know that its just a dumb mistake that I have made.

function run() {
  const quest = document.getElementById('quest');
  const data = quest.value;
  const element = document.createElement('div').innerHTML = data
  const store = document.getElementById('store');
  store.appendChild(element)
}
body {
  text-align: center;
}
<h1>Calucator</h1>
<input type="number" name="" id="quest">
<button onclick="run()">=</button>
<div id="store"></div>

Upvotes: 0

Views: 51

Answers (1)

ericmp
ericmp

Reputation: 2247

As the comments in your question pointed - document.createElement('div').innerHTML = data is not a document node element

And use .textContent instead of .innerHTML - otherwise you'll introduce an XSS vulnerability.

function run() {
    const quest = document.getElementById("quest");
    const data = quest.value;
    const yourElement = document.createElement("div");
    yourElement.textContent = data
    const store = document.getElementById("store");
    store.appendChild(yourElement);
}

What i changed in the function?

I first create the element, and then set it's text content. Finally i append it to the element you wanted.

Upvotes: 1

Related Questions