Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Object forEach is not a function

Tags:

javascript

Hi Im trying to access the child nodes of a selected element, but the browser tells me that that object doesn't have a foreach function. What should I do for me to access the child elements. I dont want to use jquery instead I want to use native, for experiment purpose.

here is my code:

var el = document.querySelector('ol');
el.children.forEach(function(childEl) {
  console.log(childEl);
})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <ol contenteditable oninput="">
    <li>press enter</li>
  </ol>
</body>

</html>
like image 643
loki9 Avatar asked Nov 29 '25 23:11

loki9


1 Answers

Node.children is dom collection, not an real array so it doesn't have array methods like forEach(need to fix the case also).

So one commonly used solution is to call the array methods with the context as the html collection

var el = document.querySelector('ol');
[].forEach.call(el.children, function(childEl) {
  console.log(childEl);
})
  <ol contenteditable oninput="">
    <li>press enter</li>
  </ol>

Another way(similar) is to convert the collection to an array first(using Array.slice()) then call array methods on it

var el = document.querySelector('ol'),
  array = [].slice.call(el.children);
array.forEach(function(childEl) {
  console.log(childEl);
})
<ol contenteditable oninput="">
  <li>press enter</li>
</ol>
like image 162
Arun P Johny Avatar answered Dec 01 '25 11:12

Arun P Johny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!