11 January 2024

To retrieve the value of an attribute using getElementsByTagName() in JavaScript, you first use the document.getElementsByTagName("tag") method, replacing "tag" with the HTML tag of the elements you're interested in, such as "div" for elements. This returns a collection of elements. Subsequently, you access a specific element from this collection, for instance, the first one using the index [0]. Once you have the desired element, you employ the getAttribute("attributeName") method to extract the value of a specific attribute, replacing "attributeName" with the name of the attribute you're targeting. This is particularly useful for custom attributes like "data-customAttribute". Finally, you can utilize this obtained attribute value as needed in your JavaScript code.

Source code viewer
  1. // Get src attribute value of the first image tag in document.
  2. const src = document.getElementsByTagName('img')[0].getAttribute('src');
Programming Language: ECMAScript