简体   繁体   中英

Why I am not able to use index method on NodeList?

For some reasons, I cannot use index method of NodeList object. When I do typeof on items of headElements I receive it as a object than node.

I want to append every node of headElements and rowElements to tr element.

Here is my code:

var pageHeads = document.getElementsByTagName('thead');
var pageBody = document.getElementsByTagName('tbody');


var headElements = pageHeads[i].querySelectorAll('td');
var rowElements = pageBody[i].querySelectorAll('td');

headElements.index(0).cloneNode(true);
var pageHeads = document.getElementsByTagName('thead');
var pageBody = document.getElementsByTagName('tbody');


var headElements = pageHeads[i].querySelectorAll('td');
var rowElements = pageBody[i].querySelectorAll('td');

headElements.item(0).cloneNode(true);

Hope this helps !

The .index() method is not a native JavaScript method, but a Jquery method. This is why you get the error headElements.index is not a function .

var headElements = pageHeads[i].querySelectorAll('td');
var rowElements = pageBody[i].querySelectorAll('td');

In addition, these two lines do not make much sense outside of a loop. i is simply a variable that stores the index of whatever pageHeads elements you which to select. Unless i is defined (inside or outside a loop), your code will return an error.

Solution

(1) Set i to the index of the pageHeads element you wish to use.

(2) To access a child element of pageHeads , simply find out its index. Use the index with bracket notation to access the child element.

var headElements = pageHeads[0].querySelectorAll('td');
headElements[0]; // This will return the first element in the headElements nodelist.

Edit

It seems you are looking for the wrong child elements in your table head.

var headElements = pageHeads[i].querySelectorAll('td');

should be:

var headElements = pageHeads[i].querySelectorAll('th');

See this fiddle

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