2015-07-21 152 views
2

嗨我试图访问所选元素的子节点,但浏览器告诉我,该对象没有foreach函数。我应该如何为我访问子元素。我不想使用jquery,而是想使用本机,以用于实验目的。Javascript对象forEach不是函数

这里是我的代码:

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

'foreach'是无效的功能,使用'forEach' *资本E *,https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/ forEach – Tushar

+0

@Tushar nope它不起作用 – loki9

回答

5

Node.childrendom collection,而不是一个真正的数组,因此不会有像forEach阵列的方法(还需要修正的情况下)。

所以一个常用的解决方法是调用与上下文作为HTML收集

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


的另一种方式的阵列方法(类似)被添加到集合转换为先阵列(使用Array.slice())然后调用它的数组方法

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>