简体   繁体   中英

Get all elements with similar id array in javascript

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?

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]" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM