getElementsByClass和appendChild

Sno*_*lax 9 javascript html5 getelementbyid appendchild css3

只是刷新我的JavaScript技巧,并试图找出为什么getElementsByClass不适用于我的代码.代码非常简单.单击"clicky"按钮后,脚本将创建div的子h1元素.当我使用getElementById并将div类更改为Id但在将其更改为class时不起作用时,它工作得很好.

我试过,getElementsByClassName,getElementsByClass,getElementsByTagName并将div更改为适当的属性但没有运气.

<!doctype html>
<html>


<body>
<p>Click on button to see how appendChild works</p>

<button onclick="myFunction()">Clicky </button>

<script>
function myFunction(){
var first = document.createElement("H1");
var text = document.createTextNode("Jason is pretty awesome");
first.appendChild(text);

document.getElementsByName("thistime").appendChild(first);

}
</script>

<div class="thistime">Hi</div>

    </body>






</html>
Run Code Online (Sandbox Code Playgroud)

Nik*_*wal 25

您需要更新代码

document.getElementsByName("thistime").appendChild(first);
Run Code Online (Sandbox Code Playgroud)

document.getElementsByClassName("thistime")[0].appendChild(first);
Run Code Online (Sandbox Code Playgroud)

供参考 - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

工作代码 - http://plnkr.co/edit/k8ZnPFKYKScn8iYiZQk0?p=preview


Ric*_*ock 7

你可以使用IE9 +支持的getElementsByClassName():

  document.getElementsByClassName("thistime")[0].appendChild(first);
Run Code Online (Sandbox Code Playgroud)

但是更好的替代方案可能是querySelector(),它在IE8 +中受支持

  document.querySelector(".thistime").appendChild(first);
Run Code Online (Sandbox Code Playgroud)

请注意,querySelector()使用CSS选择器语法,因此您应该在类之前放置一个点(.).

片段:

function myFunction() {
  var first = document.createElement("H1");
  var text = document.createTextNode("Jason is pretty awesome");
  first.appendChild(text);

  document.querySelector(".thistime").appendChild(first);
}
Run Code Online (Sandbox Code Playgroud)
<p>Click on button to see how appendChild works</p>

<button onclick="myFunction()">Clicky</button>

<div class="thistime">Hi</div>
Run Code Online (Sandbox Code Playgroud)