问题
Challenge = how to specify an array without jQuery and without NodeLists.
Currently, I use the following, with jQuery:
$('audio')
and then iterate over each <audio>
element and this definitely works. I iterate over this array with a conventional for-loop, or even using the .each
construct.
However, in an attempt to avoid jQuery and without nodeLists, I am totally clueless.
How I wish document.querySelectorAll("audio")
would be a non-jQuery equivalent of $('audio')
, but it does not appear to be. querySelectorAll("audio")
and getElementsByTagName("audio")
generate NodeLists. Not only that, but "audio" is not considered a tag. Am I to add a class or even a name to each <audio>
and use the specified class or name as a selector?
Help is definitely needed ... and very much appreciated.
回答1:
Thought I'd answer seeing as you mentioned my post :)
There are a few ways you can parse a NodeList into an Array, covered in the post.
Best bet is to create a reusable function that handles the conversion for you:
function $$(selector, scope) {
return [].slice.call((scope || document).querySelectorAll('div'));
}
Usage:
$$('.elem'); // document > .elem
$$('.elem', '.parent'); // .parent > .elem
Good luck!
来源:https://stackoverflow.com/questions/31557252/specify-an-array-without-jquery-and-without-nodelists