getElementsByClass and appendChild

后端 未结 3 1293
悲哀的现实
悲哀的现实 2021-01-04 04:19

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 \"cl

3条回答
  •  余生分开走
    2021-01-04 04:56

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

    Click on button to see how appendChild works

    Hi

提交回复
热议问题