简体   繁体   中英

Can't understand this line of JavaScript

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

.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

[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

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.

getelementsByTagName返回具有相同标签的元素数组,然后使用sortOn变量选择指定的一个表单集合,并带上他的第一个孩子,然后在上面查找。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM