Retrieving the name value of an element in JavaScript

When dealing with multiple tag elements with the same tagname, there are a few solutions. The first solution is to use “try” to get the element with the desired name. The second solution is to specify a tag name if possible, as using a generic search may return a collection of elements. If necessary, one can loop through all the elements on the page to find the desired attribute. Alternatively, libraries like jQuery can handle this task for you.

Solution 1:

To obtain the desired element, utilize


which finds the initial matching element. Subsequently,


can be used to retrieve the essential attribute from that element. In case of multiple tag elements with identical tag names, implement



var getElem = document.querySelector('preference'),
  getNameProperty = getElem.getAttribute('name');

Solution 2:



Retrieving the element with the identifier of



Solution 3:

The function assigned to


will provide a group of elements. Afterwards, you can utilize


to retrieve the name attribute of the initial element in the group.

console.log( document.getElementsByTagName( "preference" )[0].getAttribute( 'name' ) );

Frequently Asked Questions