tags:

views:

94

answers:

4

Hi,

Thanks for your attention and time.

I'm modifying an existing JavaScript but can't understand a line of code. Please help me understanding this line:

 rowArray[i].value = rows[i].getElementsByTagName('td')[sortOn].firstChild.nodeValue;

I am clear till .getElementsByTagName('td'), sortOn is being passed in this function as a parameter. But I couldn't understand [sortOn].firstChild.nodeValue;

Please guide me,

thanks

+1  A: 

rows[i].getElementsByTagName('td') will get all td elements that are children of rows[i]. The [sortOn] part selects the td whose index is specified by the sortOn parameter. The .firstChild.nodeValue gets the text contained in the first element within that td.

Update: In the DOM, elements such as <td> can only contain other child elements, but they don't have any text property. The text itself is contained in a special "text node" that is a child of the <td> node. This is why you use .firstChild to obtain the text node, then use .nodeValue to get the text contained in that node.

casablanca
thanks casablanca,it is helpful. Can you pleaes a little more explain .firstChild and .nodeValue seprately. I am confused when sortOn will spacify the cell than what will for .firstChild.nodeValue ?thanks
haansi
@haansi: I've updated the answer.
casablanca
+1  A: 

getelementsByTagName returns you an array of element with same tag, then by using sortOn variable you select specified one form collection and take his first child and look on it.

Artem Barger
+2  A: 

[sortOn] is array notation. It works in exactly the same way as rows[i]. Let's say sortOn is equal to 5, and that there are seven elements in rows[i].getElementsByTagName('td'), which is an array of <td> elements. Then you will get the sixth one (JavaScript arrays are 0 based), and this will be a <td> element.

firstChild means the first element beneath that td, so in this case

<td><em>emphasis</em><strong>some text</strong></td>

the <em> element is the first child

nodeValue is in this case the contents of that element, so "emphasis" will be returned.

You may well find the gecko DOM reference useful

Mark Chorley
+7  A: 

.getElementsByTagName('td') - returns a list of TD elements.
.getElementsByTagName('td')[sortOn] - fetches a single element from that list
.firstChild - returns the first element that is positioned inside this TD.
.nodeValue: see here - https://developer.mozilla.org/En/DOM/Node.nodeValue

AndreyKo
thanks AndreyKo,It is helpful.I am confused in one thing. When [sortOn] will move us to required td. But .firstChild I cant understnad it. please help a little more.thanks
haansi
please just explain .firstChild - returns the first element that is positioned inside this TD.In my td there will be test. That is why I am confused why it is being used. Is there any way that I can avoid it and directly accessing text. If it has some advantage please guide me.thanks
haansi