Tuesday, February 20, 2018

[JavaScript][Exercise] Function appendChildren should add a new child div to each existing div.


Function appendChildren should add a new child div to each existing div. New divs should be decorated by calling decorateDiv.
For example, after appendChildren is executed, the following divs:
<div id="a">
  <div id="b">
  </div>
</div>
should take the following form (assuming decorateDiv does nothing):
<div id="a">
  <div id="b">
    <div></div>
  </div>
  <div></div>
</div>
The code below should do the job, but for some reason it goes into an infinite loop. Fix the bugs.

Reference answer

This is a question about manipulate dom element, document.getElementsByTagName("div"); return live DOM, if you use document.createElement("div") create more DOM element, it increase value stored in allDivs and create an infinity for-loop. So you need to use a variable to store amount of your div live DOM element before you append any child.
<html>
<body>
</body>
<script>
function appendChildren(decorateDivFunction) {
  var allDivs = document.getElementsByTagName("div");
  var len = allDivs.length;

  for (var i = 0; i < len; i++) {
    var newDiv = document.createElement("div");
    decorateDivFunction(newDiv);
    allDivs[i].appendChild(newDiv);
  }
}

// Example case.
document.body.innerHTML = `
<div id="a">
  <div id="b">
  </div>
</div>`;

appendChildren(function(div) {});
console.log(document.body.innerHTML);
</script>
</html>

Reference
https://stackoverflow.com/questions/29605980/appending-child-div-to-each-div-with-for-loop

1 comment :