PDA

View Full Version : findChild.



CodeLegion
January 11th, 2007, 10:00 AM
Hi guys, just wondering if someone would be kind enough to help me understand how this bit of javascript works below.



function findChild (element, nodeName)
{
var child;

for (child = element.firstChild; child != null; child = child.nextSibling)
{
if (child.nodeName == nodeName)
return child;
}

return null;
}
I know what it basically does, but im having trouble running it through in my head clearly, as in talk it through too myself. Its apart of XML feed parser for a RSS widget i'm learning.

The for loop is what is confusing me I guess, specifically the variable and incrementing factor (child=child.nextSibling).

Any help would be greatly appreciated.

Thanks in advance.

Legion.

gvozden
January 11th, 2007, 11:21 AM
nextSiebling is like next Child in XML structure

it works like i++ but just for XML childs

child is part of tree structure type and XML is that type of data (parent-child part of it)
http://en.wikipedia.org/wiki/Tree_data_structure

CodeLegion
January 12th, 2007, 10:59 AM
Thanks man!

So would I be right in saying when child = nodeName the end value for the for loop has been reached, therefore when child doesnt = anything, the for loops' variable+increment factor (child = child.nextSibling) allow the loop to be continued for the next child objct within the element? Until it finds a value for child, which again would be where the loop would end.?

Sorry if that doesnt make sense but thats the only way i could think putting it lol. :|


Thanks again.

Legion.

CodeLegion
January 18th, 2007, 07:27 AM
Hi guys, I got another problem, im having trouble figuring out the bit of code thats in bold below.

Appreciate any help, and if you I need to post more information just say.

Thanks in advance.

Legion.


var results = new Array;

for( var item = channel.firstChild; item != null; item = item.nextSibling)
{
if( item.nodeName == 'item' )
{
var title = findChild (item, 'title');

if( title != null )
{
var link = findChild (item, 'link');
var pubDate = findChild (item, 'pubDate');
results[results.length] = {title:title.firstChild.data,
link:(link != null ? link.firstChild.data : null),
date:new Date(Date.parse(pubDate.firstChild.data))
};
}
}
}