开发者

Get elements with an id in javascript

I'd like to get all the input tags with an id. Right now, my code is:

inputs = document.querySelectorAll('input');
for (i=0; i<inputs.length; i++) {
  开发者_Go百科if (inputs[i].id) { .. }
}

I'd like something cleaner if possible. Thanks in advance.


You can look for the existence of an attribute with [attribute name]:

inputs = document.querySelectorAll('input[id]');

See the W3C docs on attribute presence selectors.


Try with this:

document.querySelectorAll('input[id]');


Something like this?

var inputs = document.getElementsByTagName('input'),
  i,
  l = inputs.length;
for (i = 0; i < l; i++)
{
  if (inputs[i].hasAttribute('id'))
  {
    //do some code
  }
}

Edit to add:
Oops, turns out hasAttribute isn't as cross-browser as I thought...

"cleanest" code steps:

  1. use jQuery
  2. $('input[id]')
  3. profit


use

inputs = document.querySelectorAll('input[id]');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜