5

I have elements like this on a html page:

<input id="serial[301888][0]" type="hidden" value="51.0100|T2-QQQ" name="serial[301888][0]">
<input id="serial[301888][1]" type="hidden" value="5.0900|T2-WWW" name="serial[301888][1]">
<input id="serial[301888][2]" type="hidden" value="11.1100|T2-XXX" name="serial[301888][2]">
<input id="serial[301888][3]" type="hidden" value="22.5600|T2-YYY" name="serial[301888][3]">
<input id="serial[301888][4]" type="hidden" value="10.2300|T2-ZZZ" name="serial[301888][4]">

Without using jQuery, how could I get all these elements into an array?

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
ACs
  • 1,325
  • 2
  • 21
  • 39
  • 1
    Is this want you want? http://stackoverflow.com/questions/6991494/javascript-getelementbyid-base-on-partial-string – Thijs Oct 08 '14 at 09:50

1 Answers1

14

You can combine JavaScript's document.querySelectorAll with CSS's ^= attribute selector:

document.querySelectorAll('[id^="serial[301888]"]');

This will generate an array of all elements whose id attributes start with "serial[301888]".

James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • 2
    Note that that's definitively *not* an Array (as requested). – David Thomas Oct 08 '14 at 14:18
  • @DavidThomas that is indeed true, but `querySelectorAll` does return an Array-like object. I doubt this wouldn't fulfil OP's requirement of it being an array as jQuery's selectors themselves do not return Array instances either. – James Donnelly Oct 08 '14 at 14:28
  • Agreed; my point wasn't that your code wouldn't work, just pointing out that it wouldn't return an array (though, of course, it does return a [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList), which is, in many ways, very similar). I was aiming for clarity, rather than criticism; but my language choices sometimes fail. – David Thomas Oct 08 '14 at 14:35