innerhtml字符串到多个元素

时间:2018-07-28 11:09:23

标签: javascript dom innerhtml

是否可以像这样将html插入类中?它不起作用,控制台中没有错误。

<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>

<script>
    var currentYear = new Date().getFullYear();
    var yearTarget = document.getElementsByClassName("yearTarget");
    yearTarget.innerHTML = currentYear;
</script>

2 个答案:

答案 0 :(得分:2)

Document.getElementsByClassName()返回类似数组的对象。您必须指定索引或遍历所有元素才能分别设置innerHTML

var currentYear = new Date().getFullYear();
var yearTarget = document.getElementsByClassName("yearTarget");
[...yearTarget].forEach(function(el){
  el.innerHTML = currentYear;
});
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>
<p class="caption">Copyright &copy; <span class="yearTarget"></span></p>

答案 1 :(得分:1)

document.getElementsByClassName(“ catlink”)选择网页中的所有元素作为数组,因此您必须使用[0]

yearTarget[0].innerHTML = currentYear;