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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With