I have a Javascript function that accepts a list of HTML nodes, but it expects a Javascript array (it runs some Array methods on that) and I want to feed it the output of Document.getElementsByTagName
that returns a DOM node list.
Initially I thought of using something simple like:
Array.prototype.slice.call(list,0)
And that works fine in all browsers, except of course Internet Explorer which returns the error "JScript object expected", as apparently the DOM node list returned by Document.getElement*
methods is not a JScript object enough to be the target of a function call.
Caveats: I don't mind writing Internet Explorer specific code, but I'm not allowed to use any Javascript libraries such as JQuery because I'm writing a widget to be embedded into 3rd party web site, and I cannot load external libraries that will create conflict for the clients.
My last ditch effort is to iterate over the DOM node list and create an array myself, but is there a nicer way to do that?
Note: Although NodeList is not an Array , it is possible to iterate over it with forEach() . It can also be converted to a real Array using Array. from() .
You can convert it to an array by using the slice method from the Array prototype: var elList = document. querySelectorAll('. viewcount'); elList = Array.
The HTML DOM NodeList Object All browsers return a NodeList object for the property childNodes . Most browsers return a NodeList object for the method querySelectorAll() .
The quickest way to convert an array of objects to a single object with all key-value pairs is by using the Object. assign() method along with spread operator syntax ( ... ). The Object.
In es6 you can just use as follows:
Spread operator
var elements = [... nodelist]
Using Array.from
var elements = Array.from(nodelist)
more reference at https://developer.mozilla.org/en-US/docs/Web/API/NodeList
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