根据文本输入更改具有特定类的所有元素

时间:2015-11-28 00:07:03

标签: javascript html

我认为这将是非常简单的事情,但我还没有找到答案。如何使用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.
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:5)

method getElementsByClassName()返回一个类似数组的数组对象。

您需要迭代每个元素并通过其索引访问它。

Working Example

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;
});

答案 1 :(得分:1)

你可以像使用Map<InetSocketAddress,Foo>一样获得一个具有某个类名的元素数组,所以没关系。

它会返回一个数组,所以你实际上必须遍历它。

答案 2 :(得分:0)

看一下jQuery,它可以帮助你解决这个问题。

您需要在标头中加入<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>并将代码更改为:

<!DOCTYPE html>
<html>
  <head>
   <title>test</title>
   <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
  </head>
  <body>
    <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.
    <script>
     function start(){
         var name = $("#name").val();
          $(".namehere").text(name);
     }
    </script>
  </body>
</html>

答案 3 :(得分:0)

你好HK0至于我记得document.getElementByClassName无法到达innerHTML(或者至少不是直接)所以我建议通过使用一个简单的for方法并获得像以下te之类的elementbyid来更简单的方法:

 <span id="namehere0"></span> is doing this and that.
 <br>
 <span id="namehere1"></span> wants to do this and that.
 <br>
 <span id="namehere2"></span> is not doing this or that.
 <br>
 <span id="namehere3"></span> wants to do this but instead is doing that.

 <script>
 function start(){
  var name = document.getElementById("name").value;
  for(var i=0;i<4;i++) document.getElementById("namehere"+i).innerHTML=name;

  }
        </script> 

希望这会有所帮助