I know the name of HTML element but not id. How to fetch id using name of the element using Javascript. Kindly help.
How to get id of an element whose name is known in Javascript
Asked Answered
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.
+1 particularly for pointing out that a name does not necessarily give a unique id. :) –
Ensphere
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'));
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.
© 2022 - 2024 — McMap. All rights reserved.
elements[0].id
– Adjacent