François Beaufort
François Beaufort

Reputation: 5659

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++) {
  if (inputs[i].id) { .. }
}

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

Upvotes: 1

Views: 238

Answers (4)

zzzzBov
zzzzBov

Reputation: 179266

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

Upvotes: 0

shankhan
shankhan

Reputation: 6571

use

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

Upvotes: -1

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99919

Try with this:

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

Upvotes: 1

lonesomeday
lonesomeday

Reputation: 238055

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.

Upvotes: 6

Related Questions