如何通过ID更改HTML元素?

时间:2020-05-01 15:27:03

标签: javascript html

这是一个初学者的问题,我正在学习一个javascript课程,它应该可以,但是不能。

在我的HTML页面中,我具有以下元素(这样做是为了使“ x1 =“和数字在同一行):

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

并且在javascript部分中,我尝试使用以下代码更改这些元素

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

但它们不会改变。我也看不到控制台中的错误。

我在做什么错了?

5 个答案:

答案 0 :(得分:2)

问题是<label>没有value属性。您必须使用textContentinnerHTML,例如:

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

答案 1 :(得分:1)

使用textContentinnerHTML

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

答案 2 :(得分:1)

请勿将value属性与<label>一起使用,例如,在<input>上使用它。因此,请改用innerHTMLinnerText

这是您的完整代码(带有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>

现场演示:https://codepen.io/marchmello/pen/abvLENr?editors=1010

这是您的代码(带有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>

答案 3 :(得分:1)

这是因为value<input>属性。要更改标签文本,您必须对其进行innerText更改。因此,将是这样的:

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

如果您的字符串包含HTML,则可以改用innerHTML。请注意,在您的示例中,我们期望x1是一个变量。

答案 4 :(得分:1)

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

也在

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

id为“#2”,但在HTML中,id为“ x2”。考虑更改

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

document.getElementById("x1").setAttribute = "x1";
document.getElementById("x2").setAttribute = "x2";
相关问题