4

I am trying to filter children of an div element.

I get direct access to the parent div via Angular ViewChild and if I print the children like this

console.log(this.myParentDiv.nativeElement.children);

I get the following output in Chrome:

enter image description here

I need to convert this to array to be able to filter the divs. However if I convert it like this

console.log(Array.from(this.myParentDiv.nativeElement.children));

It returns an empty array.

Any idea why it returns empty?

doorman
  • 15,707
  • 22
  • 80
  • 145
  • 1
    Because the collection is actually empty. See http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays – JJJ Mar 28 '17 at 10:34
  • 1
    Something should be wrong in your code. Just try to do this: `Array.from(document.body.children)` on this SO Q&A from the debugger console and see that it works.. – Matías Fidemraizer Mar 28 '17 at 10:34
  • 1
    Did you notice `HTMLCollection[0]` ? The subscript `0` shows that the collection is actually empty. What you are seeing in console are the values which got evaluated later on. Maybe the values were not there initially and you are updating the collection dynamically – abhishekkannojia Mar 28 '17 at 10:36
  • 2
    Ok, I added a delay making sure the elements were actually rendered before calling the Array.from and it works correctly now – doorman Mar 28 '17 at 10:39
  • @doorman How did you fixed? Could you share your solution? – Mesut Çiftçi Feb 28 '21 at 18:02
  • @MesutÇifci it's been a while but it seems I added a delay before calling the array action.. so try to use setInterval – doorman Mar 03 '21 at 16:11

2 Answers2

0

I think the problem in this case is that the Javascript code is being executed before the html document is ready.

Move your JS code or import to the bottom of the page and the problem should be fixed.

-1

Not the fanciest solution but in order to achieve this I wrapped the logic into a timeout function:

setTimeout(() => {
  const elementChildren = this.myParentDiv.nativeElement.children;
        
  // regular for loop
  for (let i = 0; i < elementChildren.length; i++) {
    console.log(">>",elementChildren[i]);
  }              
}, 100);
Diego Borigen
  • 545
  • 4
  • 6