问题
Here's the step through of the javascript.
I have an HTMLCollection, I want to loop through it and extract the object with the ID of FileUploadControl. How do I do it?
Here's my code, how do I proceed?
function uploadImage(lnk)
{
var row = lnk.parentNode.parentNode;
var rowIndex = row.rowIndex - 1;
var abc = row.cells[2].getElementsByTagName("input");
var arr = [].slice.call(abc);
}
回答1:
This would do it:
abc.namedItem('FileUploadControl')
But beware that:
Different browsers behave differently when there are more than one elements matching the string used as an index (or namedItem's argument). Firefox 8 behaves as specified in DOM 2 and DOM4, returning the first matching element. WebKit browsers and Internet Explorer in this case return another HTMLCollection and Opera returns a NodeList of all matching elements.
From here.
This means that if in your markup you had something like this:
<div id='id'>Foo</div>
<div id='id'>Bar</div>
browsers would behave differently when executing the following code:
document.getElementsByTagName('div').namedItem('id')`
Firefox would return an HTMLElement, while IE would return another HTMLCollection.
To solve this inconsistencies, you could apply a function to return the same object.
retElement( abc.namedItem('id') );
Which could be something like this:
var retElement = function(oElem) {
//Firefox
if (oElem instanceof window.HTMLElement)
return oElem;
//IE and WebKit
if (oElem instanceof window.HTMLCollection)
return oElem.item(0);
};
来源:https://stackoverflow.com/questions/33281268/how-do-i-extract-the-name-from-html-collection