同名类元素

时间:2016-08-24 10:51:06

标签: element

我如何改变2级" myDiv"跨度名称同时?下面的脚本仅适用于第一个" myDiv"

<div class="myDIV">
  <span>orginial name1</span>
</div>

<div class="myDIV">
  <span>orginial name2</span>
</div>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var x = document.getElementsByClassName("myDIV");
    x[0].innerHTML = "<span>new name for all</span>";
}
</script>

1 个答案:

答案 0 :(得分:0)

有时会忘记一些简单的事情,只需添加x[1].innerHTML = "<span>new name for all 2</span>";

即可

function myFunction() {
    var x = document.getElementsByClassName("myDIV");
    x[0].innerHTML = "<span>new name for all 1</span>";
    x[1].innerHTML = "<span>new name for all 2</span>";
}
<div class="myDIV">
  <span>orginial name1</span>
</div>

<div class="myDIV">
  <span>orginial name2</span>
</div>

<button onclick="myFunction()">Try it</button>