How to get id of an element whose name is known in Javascript

John Watson picture John Watson · Mar 5, 2012 · Viewed 48.4k times · Source

I know the name of HTML element but not id. How to fetch id using name of the element using Javascript. Kindly help.

Answer

Sirko picture Sirko · Mar 5, 2012
var elements = document.getElementsByName( 'yourname' );
var id = elements[0].getAttribute( 'id' );

docu @ MDN

If you have multiple elements of that name, you will have to run though the array of elements and pick the right one. If there is just one, the above code will work.