Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu May 21, 2023 › #Attribute #Element

How to Get All the Attributes of a DOM Element with JavaScript

In this article, we will explore how to get all the attributes of a DOM element using JavaScript.

We'll cover three methods - using the forEach() method, attributes property and using the spread operator - to achieve this.

Using the forEach() method#


  1. This code snippet retrieves all the attributes and their values of an HTML element with the ID my-element using the getElementById() method from the document object.
    const element = document.getElementById('my-element');
    
  2. Then, an empty object called attributes is created to store the attributes and their values.
    const attributes = {};
  3. Next, all the attributes of the element are converted into an array and iterated over using the forEach() method. Inside the iteration, each attribute's name and value are added to the attributes object.
    Array.from(element.attributes).forEach((attr) => {
      attributes[attr.name] = attr.value;
    });
  4. Finally, the attributes object is logged to the console.
    console.log(attributes);

Accessing the element's attributes property directly#

Another way to get all the attributes of a DOM element is by accessing the attributes property directly. This property contains a collection of all the attributes of an element. Here's an example:

const element = document.getElementById('my-element');
const attributes = element.attributes;
console.log(attributes);

By assigning the attributes property of the element to a variable, we get access to all the attributes as a collection. Then, you can iterate over this collection or access individual attributes using their index.

Utilizing the spread operator and Array.from()#

In this example, we will use the spread operator to convert the attributes collection into an array. Here's an example:

By spreading the element.attributes directly into an array, you can retrieve all the attributes in a single line of code. This technique is particularly useful if you plan to perform further array operations or use array methods on the attributes collection.

save
listen
AI Answer
Write Your Answer
loading
back
View All