7

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

CPC
  • 163
  • 5
  • 17
John Watson
  • 869
  • 3
  • 16
  • 32

3 Answers3

21
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.

Sirko
  • 72,589
  • 19
  • 149
  • 183
5

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

Ayush
  • 41,754
  • 51
  • 164
  • 239
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