0

I'm trying to insert HTML codes into a div Class, But It doesn't seem to work. I have included my code below. Need some help in inserting an HTML code in Javascript.

Using .getElementById works:

document.getElementById('test1').innerHTML = '<div id=test11>Test 1!</div>';
<span id="test1"></span>

But using getElementsByClassName nothing happened:

document.getElementsByClassName('test2').innerHTML = '<div id=test22>Test 2!</div>';
<span class="test2"></span>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Cloud Sky
  • 117
  • 2
  • 8
  • *"But using getElementsByClassName nothing happened"* Something happened. :-) Open your web console to see what. The linked question's answers explain why, and what to do instead. In this case, if you just want to change the *first* element with that class, use `document.querySelector(".test2")`. If you want to change them all, use a loop. Happy coding! – T.J. Crowder Jul 14 '18 at 10:07
  • Do like this document.getElementsByClassName('test2')[0].innerHTML = '
    Test 2!
    '; getElementsByClassName returns array so get 0th element
    – Yamini Chhabra Jul 14 '18 at 10:09

0 Answers0