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

document.querySelector

which finds the initial matching element. Subsequently,

getAttribute

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

document.querySlectorAll

.

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


Solution 2:

Try:

document.getElementsByName("webviewbounce");

Retrieving the element with the identifier of

webviewbounce

.


Solution 3:


The function assigned to

getElementsByTagName

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

getAttribute()

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

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

Frequently Asked Questions