How do I extract the name from HTML collection?

2019-09-10 02:23发布

Here's the step through of the javascript.

enter image description here

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条回答
贪生不怕死
2楼-- · 2019-09-10 03:07

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);
};
查看更多
登录 后发表回答