-3

I am trying to add a div inside a nested divs structure in one of my project.

below is the sample I wrote to replicate the behavior. what could possibly be going wrong with it that I am not able to see widget div after clicking the button?

function myFunction() {
  var widget = document.createElement("div");
  widget.id = 'widget';
  widget.innerHTML = "I am Widget";
  var x = document.getElementsByClassName("model-viewer");
  x[0].appendChild(widget);

  console.log(x)
  x[0].innerHTML = "Hello World!";
}
<div class="example">First div element with class="example".
  <div class="app_main">
    <div class="model"></div>
    <div class="model-filter">
      <div class="model-viewer">hello</div>
    </div>
    <div class="mod"></div>
  </div>
</div>

<button onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
connexo
  • 53,704
  • 14
  • 91
  • 128
SIM
  • 73
  • 1
  • 14
  • 1
    Is the question how to do this in IE8? Addendum: See [javascript document.getElementsByClassName compatibility with IE](https://stackoverflow.com/questions/7410949/javascript-document-getelementsbyclassname-compatibility-with-ie). I'm voting to close. – Theraot Jun 02 '19 at 08:44

1 Answers1

4

You are appending the widget successfully, but then you overwrite it with innerHTML immediately afterward.

Once you call the appendChild function, your HTML looks like this:

<div class="model-viewer">
  hello
  <div id="widget">
    I am Widget
  </div>
</div>

Then you call innerHTML and it replaces all the code inside .modal-viewer (including the #widget).


You could use insertAdjacentHTML to append the widget after the element instead.

function myFunction() {
  var widget = document.createElement("div");
  widget.id = 'widget';
  widget.innerHTML = "I am Widget";
  var x = document.getElementsByClassName("model-viewer");

  // x[0].appendChild(widget); // OLD WAY
  x[0].insertAdjacentHTML('afterEnd', widget.innerHTML); // NEW WAY

  console.log(x)
  x[0].innerHTML = "Hello World!";
}
<div class="example">First div element with class="example".
  <div class="app_main">
    <div class="model"></div>
    <div class="model-filter">
      <div class="model-viewer">hello</div>
    </div>
    <div class="mod"></div>
  </div>
</div>

<button onclick="myFunction()">Try it</button>

<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
Gary Thomas
  • 2,291
  • 1
  • 9
  • 21
  • My bad, thanks for notifying a silly mistake. I copied the sample from tryitEditor and forgot to remove that last line – SIM Jun 02 '19 at 09:32