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

3

7

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

Radley answered 5/3, 2012 at 11:26 Comment(0)
T
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.

Temporary answered 5/3, 2012 at 11:28 Comment(2)
Yes, or, simply elements[0].idAdjacent
+1 particularly for pointing out that a name does not necessarily give a unique id. :)Ensphere
E
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

Energetic answered 5/3, 2012 at 11:37 Comment(0)
F
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.

Felt answered 5/3, 2012 at 12:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.