简体   繁体   中英

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?

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;

Use textContent or innerHTML

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

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>

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM