I am trying to iterate through a NodeList using foreach. When I try to access with the following code, I get undefined in the console.
foreach = Array.prototype.forEach;
cls= document.getElementsByClassName('classname')
foreach.call(cls,function(some)
{
var ok = some.children;
foreac.call(ok,function(ss)
{
ss
});
});
I am trying this code in chrome developer tools. The console is returning 'undefined'. I am able to access by explicitly specifying the list position.
You are getting undefined
because basically you are not doing anything with the result. You can return it or e.g. log it to the console.
var foreach = Array.prototype.forEach,
cls = document.getElementsByClassName('classname');
foreach.call(cls, function(some) {
var ok = some.children;
foreach.call(ok, function(ss) {
console.log(ss);
});
});
<ul class='classname'>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Anyways I'm not sure if you are doing this for only learning purposes or not, but you are complicating it.
Wouldn't be it easier to just get the specified elements with querySelectorAll
and iterate over it with Array#forEach
?
var elems = document.querySelectorAll('ul li');
elems.forEach(v => console.log(v));
<ul class='classname'>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>