-3

How can I write the function which receives an array of objects as parameters like name and age. The function has to add in the end of the body tag using a html list which has the format name, age.

<html>
    <head>
        <title>Ex2</title>
    </head>
    <body>
      <script>
          var body = document.querySelector('body');
          body.append('Name Age');
      </script>
    </body>
</html>
Libra
  • 2,544
  • 1
  • 8
  • 24
  • 2
    Did you attempt at all to google this? Literally the first result is a link to [this question](https://stackoverflow.com/questions/13495010/how-to-add-content-to-html-body-using-js/13495046). – Libra Jan 06 '20 at 21:30
  • I need to use the array of objects in the parameter of the function. – Ioana Renard Jan 06 '20 at 21:35
  • 1
    @IoanaRenard Pure code-writing requests are off-topic on Stack Overflow — we expect questions here to relate to *specific* programming problems — but we will happily help you write it yourself! Tell us [what you've tried](https://stackoverflow.com/help/how-to-ask), and where you are stuck. This will also help us answer your question better. In addition, this question is not topically related to CSS. – Libra Jan 06 '20 at 21:36
  • `var doc = document, bod = doc.body, textNode = doc.createTextNode('Name Age'); bod.appendChild(textNode)` – StackSlave Jan 06 '20 at 21:40

1 Answers1

1

You can try the below snippet

function addList(arr) {
  var body = document.getElementsByTagName('body')[0];
  var ul = document.createElement('ul');
  for (var i = 0, n = arr.length; i < n; ++i) {
    var li = document.createElement('li');
    li.innerHTML = `${arr[i].name} ${arr[i].age}`;
    ul.append(li);
  }
  body.append(ul);
}

addList([
  { name: 'Nikhil', age: 27 },
  { name: 'Nik', age: 26 }
]);
<html>
  <body>
  </body>
</html>
Nikhil Goyal
  • 1,945
  • 1
  • 9
  • 17