本文介绍了getElementsByClass和appendChild的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是刷了我的javascript技能,并试图找出为什么getElementsByClass不工作我的代码。代码很简单。在点击按钮clicky时,脚本将创建一个div的h1元素。当我使用getElementById和将div类更改为Id时,它工作得很好,但是当我将其更改为类时,它不工作。

just brushing up on my javascript skills and trying to figure out why getElementsByClass isn't working for my code. The code is pretty simple. Upon clicking a button "clicky", the script will create a child h1 element of div. It works perfectly fine when I use getElementById and changing the div class to Id but doesn't work when I change it to class.

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

I've tried, getElementsByClassName, getElementsByClass, getElementsByTagName and changing the div to the appropriate attribute but no luck.

<!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>


推荐答案

您需要更新

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

document.getElementsByClassName("thistime")[0].appendChild(first);

参考 -

工作代码 -

这篇关于getElementsByClass和appendChild的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 08:46