这个功能可以做得更快吗?(Can this function be made faster? Javascript)

我有一个函数可以在div中获取DOM元素数组(基于标签)。

Pseudocode: 1. Say I wanted to get all input and textarea elements within a table myTbl 2. Declare resultingArray = null 3. For each tag (ex: input, textarea) 4. tagArray = Get all elements based on tag 5. Create another array by manually looping through tagArray and adding it to resultingArray (the return type is dynamic collection and not an array.

功能上,它可以工作,但需要很长时间。 有办法做我想要做的更快吗?

I have a function that gets an array of DOM elements (based on tags) within a div.

Pseudocode: 1. Say I wanted to get all input and textarea elements within a table myTbl 2. Declare resultingArray = null 3. For each tag (ex: input, textarea) 4. tagArray = Get all elements based on tag 5. Create another array by manually looping through tagArray and adding it to resultingArray (the return type is dynamic collection and not an array.

Functionally, it works but it takes too long. Is there a way to do what I am trying to do faster?

最满意答案

基于Ben的元素思想 ,这是另一个非嵌套循环的镜头。

var tagNames = { 'SELECT' : true, 'INPUT' : true, 'TEXTAREA' : true }; //use an object for faster lookups var rawElemsArray = document.getElementById("form-name").elements; var elems = []; for (var i = rawElemsArray.length - 1; i >= 0; i--) { if (tagNames[rawElemsArray[i].tagName]) { elems.push(rawElemsArray[i]); } }

编辑: form.elements是在0级DOM中定义的,所以我敢打赌它是跨浏览器的。 如果符合您的目的,您也可以使用childNodes (也是跨浏览器)。 它们之间的区别在于childNodes选择所有节点(div,p,span等)以及空文本节点(在非IE浏览器中),而elements仅返回表单控件。

Based on Ben's elements idea, here's another shot with a non nested loop.

var tagNames = { 'SELECT' : true, 'INPUT' : true, 'TEXTAREA' : true }; //use an object for faster lookups var rawElemsArray = document.getElementById("form-name").elements; var elems = []; for (var i = rawElemsArray.length - 1; i >= 0; i--) { if (tagNames[rawElemsArray[i].tagName]) { elems.push(rawElemsArray[i]); } }

EDIT: form.elements is defined in level 0 DOM, so I bet it is cross-browser. You can also use childNodes (which is cross-browser too) if that serves your purpose. The difference between them is that childNodes selects all nodes (div, p, span etc) and also empty text nodes (in non-IE browsers) while elements returns only the form controls.

更多推荐