I know the name of HTML element but not id. How to fetch id using name of the element using Javascript. Kindly help.
Asked
Active
Viewed 5.9k times
3 Answers
21
var elements = document.getElementsByName( 'yourname' );
var id = elements[0].getAttribute( 'id' );
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.

Sirko
- 72,589
- 19
- 149
- 183
-
Yes, or, simply `elements[0].id` – Mr Lister Mar 05 '12 at 11:34
-
1+1 particularly for pointing out that a name does not necessarily give a unique id. :) – Chris Mar 05 '12 at 11:34
2
Sirko's way is correct. Just in case you (or anyone else) are interested, here's the weird- ternary-operator-javascript style of doing it:
var id = ( typeof (el = document.getElementsByTagName("div")[0]) != "undefined" ) ? el.getAttribute("id"):"Element does not exist";
have fun:-D
EDIT: decreased the readability by putting it all on one line. Please note the global Namespace pollution which saved one query.This style also prevented a possible error which could occur in Sirkos Code.

Christoph
- 50,121
- 21
- 99
- 128