Alex
Alex

Reputation: 44305

How to change a HTML element by id?

This is a beginner question, I am following a javascript course, and it should work but it does not.

In my HTML page I have the following elements (done that way so the "x1=" and the number are on the same line):

<section id="results">
  Solutions
  <p></p>
  x1=<label id="x1">0</label>
  <p></p>
  x2=<label id="x2">0</label>
</section>

and in the javascript part I try to change these elements with the following code

document.getElementById("x1").value = x1;
document.getElementById("x2").value = x2;

but they do not change. I also do not see an error in the console.

What am I doing wrong?

Upvotes: 2

Views: 2333

Answers (5)

Felippe Regazio
Felippe Regazio

Reputation: 389

Its because value is an <input> property. To change a label text you must change it innerText. So, it will be be something like that:

document.getElementById("x1").innerText = x1;

If your string contains HTML, you can use innerHTML instead. Note that in your example we are expecting x1 to be a variable.

Upvotes: 1

Justin Liu
Justin Liu

Reputation: 621

document.getElementById("x1").setAttribute = "x1";
document.getElementById("#2").setAttribute = "x2";

also in

document.getElementById("#2").setAttribute = "x2";

the id is "#2" but in HTML the id is "x2". Consider changing the

document.getElementById("x1").setAttribute = "x1";
document.getElementById("#2").setAttribute = "x2";

to

document.getElementById("x1").setAttribute = "x1";
document.getElementById("x2").setAttribute = "x2";

Upvotes: 1

Piotr Duperas
Piotr Duperas

Reputation: 26

Use textContent or innerHTML

document.getElementById("x1").innerHTML = x1;

Upvotes: 1

MARSHMALLOW
MARSHMALLOW

Reputation: 1395

Don't use the value property with <label>, use it on <input> for example. So, use innerHTML or innerText instead.

Here is your full code (with innerHTML):

let x1 = 2;
let x2 = 5;

document.getElementById("x1").innerHTML = x1;
document.getElementById("x2").innerHTML = x2;
<section id="results">
  Solutions
  <p></p>
  x1=<label id="x1">0</label>
  <p></p>
  x2=<label id="x2">0</label>
</section>

A living demo: https://codepen.io/marchmello/pen/abvLENr?editors=1010

And here is your code (with innerText):

let x1 = 2;
let x2 = 5;

document.getElementById("x1").innerText = x1;
document.getElementById("x2").innerText = x2;
<section id="results">
  Solutions
  <p></p>
  x1=<label id="x1">0</label>
  <p></p>
  x2=<label id="x2">0</label>
</section>

Upvotes: 1

palaѕн
palaѕн

Reputation: 73896

The issue is <label> does not have a value property. You have to either use textContent or innerHTML like:

document.getElementById("x1").textContent = x1;
document.getElementById("x2").textContent = x2;

Upvotes: 2

Related Questions