如何用相同的数据填充页面上的几个元素(具有相同的类)?

时间:2019-11-01 15:14:43

标签: javascript getelementbyid getelementsbyclassname

我了解如何显示当前年份并通过ID传递年份,但是该ID当然只会显示一次。我需要能够在整个站点中多次显示它。

我如何做到这一点?

//get year 
var yyyy = new Date().getFullYear();

currYear.innerHTML = yyyy;


//trying to display as a class
document.getElementsByClassName('thisYear')[0] = yyyy;
<span id="currYear"></span>
<span class="thisYear"><span>

3 个答案:

答案 0 :(得分:3)

据我了解,您正在尝试将当前年份添加到HTML中的多个元素中?当前,您仅将其分配给第一个([0])。 您可以使用类thisYear解析每个元素,并将当前年份添加到它们中。

//get year 
var yyyy = new Date().getFullYear();

//trying to display as a class
//the document.getElementByClassName returns a htmlCollection. not an array directly.
//https://stackoverflow.com/a/3871602/5784924
Array.from(document.getElementsByClassName('thisYear')).forEach(function(element) {
  element.innerHTML = yyyy;
});
<div class="thisYear">this year</div><br>
<div class="thisYear">this year</div><br>
<div class="notThisYear"> not this year</div><br>
<div class="notThisYear">not this year</div><br>
<div class="thisYear"></div>

P.S。。此答案仅反映OP的要求。如果您希望看到更多最新信息并且兼容浏览器,请参阅Scott Marcus' answer

答案 1 :(得分:2)

document.getElementsByClassName('thisYear')[0] = yyyy;尝试将调用返回的DOM元素设置为年份,而不是将DOM元素的某些属性设置为Year。

要使您的代码正常工作,“快速修复”是在行中添加.innerHTML

document.getElementsByClassName('thisYear')[0].innerHTML = yyyy;
  

不过,.getElementsByClassName()(以及来自   1990年代,例如getElementsByTagName()getElementsByName()和   其他)。我已经写过这个和这个主意   向返回节点列表的方法的末尾添加索引的过程   here

相反,请使用符合标准的现代标准.querySelector().querySelectorAll(),然后您需要遍历集合并分别修改元素。

请参见其他注释:

//get year 
var yyyy = new Date().getFullYear();


// .querySelectorAll returns a node list, which is not an actual Array implementation.
// IE doesn't support calling .forEach on node lists, so if you need to support IE
// you'll need to convert the node list into an aray in order to call .forEach and you'll
// need to do it in a way that IE understands (not Array.from()):

// Array.prototype.slice.call(document.querySelectorAll('.thisYear')).forEach(function(element) {

// But, if you are not concerned with IE, you can call .forEach() directly on the node list
document.querySelectorAll('.thisYear').forEach(function(element) {
  // When the content you wish to update doesn't contain any HTML, don't use .innerHTML
  // which has performance and potential security implications, use .textContent instead
  element.textContent = yyyy;
});
div { margin-bottom:1em; }
<div class="thisYear">this year</div>
<div class="thisYear">this year</div>
<div class="notThisYear"> not this year</div>
<div class="notThisYear">not this year</div>
<div class="thisYear"></div>

答案 2 :(得分:0)

我想您正在尝试将当前日期分配给具有同一类的多个元素。请在下面查看此示例。

var items = document.getElementById( 'items' ),
    divs = document.getElementsByClassName( 'count' );

[].slice.call( divs ).forEach(function ( div ) {
    div.innerHTML = items.innerHTML;
});

来源: Replace innerHTML of all divs with same class