我认为这将是非常简单的事情,但我还没有找到答案。我如何让所有带有 class="namehere"
的 span 元素显示输入文本中插入的内容?
function start() {
var name = document.getElementById("name").value;
document.getElementByClassName("namehere").innerHTML = name;
}
<input id="name" type="text" value="Type name here">
<button type="button" onclick="start()">start</button>
<br>
<br>
<span class="namehere"></span> is doing this and that.
<br>
<span class="namehere"></span> wants to do this and that.
<br>
<span class="namehere"></span> is not doing this or that.
<br>
<span class="namehere"></span> wants to do this but instead is doing that.
最佳答案
method getElementsByClassName()
返回类似数组的元素对象。
您需要遍历每个元素并通过其索引访问它。
var nameElements = document.getElementsByClassName('namehere');
for (var i = 0; i < nameElements.length; i++) {
nameElements[i].textContent = document.getElementById('name').value;
}
或:
var nameElements = document.getElementsByClassName('namehere');
Array.prototype.forEach.call(nameElements, function (el) {
el.textContent = document.getElementById('name').value;
});
关于javascript - 根据文本输入更改具有特定类的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33966265/