I have an array scraped from a webpage:
myvar = document.querySelectorAll('#tblItineraryModuleStayDetail > tbody > tr')
Which in the console returns an array:

What I need to do is subset this array:
So I need a subset of my var with items 3 and 5 in it.
I tried: myvar.slice(3,5). This returned error "Undefined is not a function"
Had I been successful I would have an array with 3 items. I'd then need to subset on keeping odd items in the array.
How do I subset for myvar so that I have a variable with items 3 and 5 left in it? If myvar was length 10. How would I subset it to include items 3, 5, 7, 9?
I tried: myvar.slice(3,5). This returned error "Undefined is not a function"
Yes, because querySelectorAll returns a node list and not an array. See also Fastest way to convert JavaScript NodeList to Array?.
How do I subset for myvar so that I have a variable with items 3 and 5 left in it? If myvar was length 10. How would I subset it to include items 3, 5, 7, 9?
You'd need to do that manually anyway, there is no such method in javascript for slicing subsequences with steps. Use
var arr = [],
myvar = document.querySelectorAll('#tblItineraryModuleStayDetail > tbody > tr');
for (var i=3; i<myvar.length; i+=2)
arr.push(myvar[i]);
(or, if you want to be fancy)
var arr = Array.prototype.filter.call(document.querySelectorAll('#tblItineraryModuleStayDetail > tbody > tr'), function(_, i) {
return i%2==1 && i>2;
});
myvar = document.querySelectorAll('#tblItineraryModuleStayDetail > tbody > tr')
myvar is a nodeList and it's not an array. So you can't use array functions in there.
But you can use apply or call to get the array functionality on nodelist.
How to get those functionality?
Array.prototype.slice.call(myvar, 3,5);
Now you can use slice in the nodelist.
But for your actual question, to get only subset matching particular criteria is not possible via slice as well.
You must iterate through the elements and do it manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With