How to get id of an element whose name is known in Javascript
50,458
Solution 1
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.
Solution 2
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'));
Solution 3
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.
Author by
John Watson
Updated on February 22, 2020Comments
-
John Watson over 4 years
I know the name of HTML element but not id. How to fetch id using name of the element using Javascript. Kindly help.