在javascript中更改线条颜色

Chr*_*rie 1 html javascript css

我想在单击按钮时更改第2行的背景颜色,但唯一改变的是整个背景.

function changeColor() {
  document.body.style.backgroundColor = "black";
  document.getElementByID("Div2").style.backgroundColor = "black";

}
Run Code Online (Sandbox Code Playgroud)
<div id="Div2">

  <div>Line 1</div>
  <div2 class="line">Line 2</div2>
  <div>Line 3</div>
  <button onclick="changeColor()">Change color</button>
Run Code Online (Sandbox Code Playgroud)

Cra*_*ppy 5

试试这个:

<div id = "Div2">

<div>Line 1</div>  
<div id="line">Line 2</div>  
<div>Line 3</div>  
<button onclick="changeColor()">Change color</button>

<script>
    function changeColor(){
      var line = document.getElementById("line");
      line.style.backgroundColor = "black"; 
      line.style.color = "white";    
    }
 </script>
Run Code Online (Sandbox Code Playgroud)

你做错了几件事:

  1. div2 不是有效的HTML标记
  2. getElementByID() 一定是 getElementById()
  3. getElementById()使用idas参数返回具有此id的元素.所以你必须给你的行一个id:<div id="line">Line 2</div>

编辑:添加白色字体颜色