Specify an array without jQuery and without NodeLists

余生颓废 提交于 2019-12-25 04:48:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!