3

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>

2

1 Answer 1

5

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.