getElementsByClass and appendChild

纵然是瞬间 提交于 2019-12-01 04:11:42

You need to update your code from

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

to

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

For reference - https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

Working code - http://plnkr.co/edit/k8ZnPFKYKScn8iYiZQk0?p=preview

You could use getElementsByClassName(), which is supported in IE9+:

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

But a better alternative may be querySelector(), which is supported in IE8+

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

Note that querySelector() uses CSS selector syntax, so you should place a dot (.) before the class.

Snippet:

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

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

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

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

As you have noticed, the function is called getElementsByName with "elements" being a plural.

It returns a list of markups by their name (and not their css class).

You need to use the function that handles the class name, and get the first element of the array, or loop on all the results, depending on what you are looking for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!