0

I wrote a function which reads a list of numbers in the html and writes them in an array, it worked fine:

function initialize(id){

  images = [];

  function PushIn_images(item) {
    images.push(item.innerHTML);}

  document.getElementById("images"+id).childNodes.forEach(PushIn_images);
  console.log(images)}

initialize(105)
<div id="images105"><p>490</p><p>491</p><p>492</p><p>493</p><p>494</p><p>495</p><p>496</p><p>497</p></div>

Then I wanted to make this function a constructor which writes the same information in the object's property it creates. But it says that the property is undefined, although I have explicitly declare it as an array:

function initialize(id){
    this.id = id
    this.images = new Array();

    function PushIn_images(item) {
      this.images.push(item.innerHTML);}

    document.getElementById("images"+this.id).childNodes.forEach(PushIn_images);
  }

  var img_list = new initialize(105);
  console.log(img_list.images)
<div id="images105"><p>490</p><p>491</p><p>492</p><p>493</p><p>494</p><p>495</p><p>496</p><p>497</p></div>

Why doesn't it work? How can I fix it to achieve what I want?

0 Answers0