无法在标识

时间:2017-07-28 15:19:26

标签: javascript css

尝试在JS中设置类名时,我收到错误Cannot set property 'className' of null。我的JS是这样的:

setInterval(function(){
  $.get('/price',function(data) {
      document.title = `($${data.price}) The Price`;
      document.getElementById("p4").innerHTML = `$${data.change}`;
      document.getElementById("p4").className = "increase";
      document.getElementById("p5").className = "triangle-down";
  });
}, 30000);

HTML中的行是:

<h1 class="decrease" id="p4">$5<i class="triangle-up" id="p5"></i></h1>

我总是得到同样的错误。但是,如果我在下面注释掉它的作品:

document.getElementById("p4").innerHTML = `$${data.change}`;

我在这里做错了什么?

4 个答案:

答案 0 :(得分:0)

您正在更改h1标签的内部:

document.getElementById("p4").innerHTML = `$${data.change}`;

结果是什么:

`$${data.change}`

确保以上变量返回以下html :(编辑:我的意思是以下格式)

<h1 class="decrease" id="p4">$5<i class="triangle-up" id="p5"></i></h1>

答案 1 :(得分:0)

代码中的解释

setInterval(function(){
  $.get('/price',function(data) {
      document.title = `($${data.price}) The Price`;
      // Step by step:    
      // You change innerHTML of id=p4, but your new html might not 
      // contents the <i class="triangle-up" id="p5"></i>
      document.getElementById("p4").innerHTML = `$${data.change}`;

      // you changing class of p4 this is ok
      document.getElementById("p4").className = "increase"

      // you are trying to change class of p5, but two lines above you
      // replaced it by $${data.change} that probably don't contains 
      // div with id=p5 and it looks like there is no more div id=p5 on the page
      // that also explains why everything is ok if you comment this line
      document.getElementById("p5").className = "triangle-down"
  });
}, 30000);

答案 2 :(得分:-2)

可以尝试:

document.getElementById("p4").classList.remove('decrease');
document.getElementById("p4").classList.add('increase');
document.getElementById("p5").classList.remove('triangle-up');
document.getElementById("p5").classList.add('triangle-down');

答案 3 :(得分:-2)

你可能错过了冒号';'在两个className分配的末尾?