Why childNodes[i] in function return undefined but alert an object?
Well, i'm writting my own getElementByClassName and this is my problem :
function getElementByClassName(elemento,clase){
var i = 0;
if(elemento.hasChildNodes()){
while(elemento.childNodes[i]){
if(elemento.childNodes[i].nodeType != 3){
if(elemento.childNodes[i].className == clase){
return elemento.childNodes[i]; // <---- This is my problem, change to alert
}
else {
getElementByClassName(elemento.childNodes[i],clase);
}
}
i++
}
}
}
var div = getEl开发者_开发问答ementByClassName(document.body,"foo");
alert(div);
It alerts undefined, but if i put ( in function) alert this alerts [objectHTMLDivElement] and undefined, so why this returns undefined if this recognize that's a [objectHTMLDivElement] with alert?
To answer your question, the reason why your implementation is not working is because you're recursively calling your function in the else
clause and doing nothing with the return value. That's why your code is finding the object, but it's never getting returned.
This is a slightly reworked version of yours, but there are also other limitations to your approach, one being elements with multiple classes will not be found (i.e. <div class="foo bar">
will not be returned). Unless you're just doing this as a learning exercise, I suggest going with an existing implementation, like the link in Yoni's answer.
function getElementByClassName(elemento, clase)
{
var i = 0;
if (elemento.hasChildNodes())
{
while (elemento.childNodes[i])
{
if (elemento.childNodes[i].nodeType != 3)
{
if (elemento.childNodes[i].className == clase)
return elemento.childNodes[i];
else
{
var result = getElementByClassName(elemento.childNodes[i], clase);
if (result != null)
return result;
}
}
i++;
}
}
return null;
}
精彩评论