Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript getElementById based on a partial string

I need to get the ID of an element but the value is dynamic with only the beginning of it is the same always.

Heres a snippet of the code.

<form class="form-poll" id="poll-1225962377536" action="/cs/Satellite"> 

The ID always starts with poll- then the numbers are dynamic.

How can I get the ID using just JavaScript and not jQuery?

like image 863
calebo Avatar asked Aug 09 '11 04:08

calebo


1 Answers

You can use the querySelector for that:

document.querySelector('[id^="poll-"]').id; 

The selector means: get an element where the attribute [id] begins with the string "poll-".

^ matches the start
* matches any position
$ matches the end

jsfiddle

like image 163
A1rPun Avatar answered Oct 06 '22 01:10

A1rPun