Search code examples
javascripthtmlgetelementsbyname

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


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


Solution

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