Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 441
John Watson Avatar asked Mar 05 '12 11:03

John Watson


2 Answers

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.

like image 161
Sirko Avatar answered Nov 15 '22 05:11

Sirko


Sirko's way is correct. Just in case you (or anyone else) are interested, here's the jquery way of doing it:

alert($("*[name='foo']").attr('id'));

DEMO

like image 44
xbonez Avatar answered Nov 15 '22 05:11

xbonez