rguttersohn
rguttersohn

Reputation: 484

How do I add HTML attributes to an array using Javascript

I am trying to add attributes from three HTML elements to an array.

Here is some sample HTML:

<p x="30">Paragraph 1</p>
<p x="50">Paragraph 2</p>
<p x="100">Paragraph 3</p>

Here is the Javascript that has gotten me closest to the results I am looking for:

const paragraphs = document.querySelectorAll(`p`);
      let i;
      for (i = 0; i < paragraphs.length; i++) {
        let dataSetOne = paragraphs[i].getAttribute('x');
        let dataSetOneArray = Array.from(dataSetOne);

      }

When I console.log(dataSetOne), I get "30" "50" "100", which is what I hoped for.

When I try to add these attributes to an array using Array.from(dataSetOne), I end up with three arrays that look like this: Array(1) [ "3", "0" ]; Array(2) [ "5", "0" ] Array(3) [ "1", "0", "0" ].

The array I am looking for is this: Array ["30", "50", "100"]

I have tried a few other functions, but none of these are getting me any closer to the result I am looking for.

This is not for a specific project. I am trying to advance my understanding of arrays and object-oriented programming.

Thanks in advance for your help.

Upvotes: 0

Views: 1412

Answers (2)

Mamun
Mamun

Reputation: 68933

Array.from()

The Array.from() method creates a new, shallow-copied Array instance from an array-like or iterable object.

Since you are using Array.from() inside of the for loop in each iteration new array is creating. You can simply declare the array (dataSetOneArray) outside of the loop and push the attribute value directly.

const paragraphs = document.querySelectorAll(`p`);
let dataSetOneArray = [];
let i;
for (i = 0; i < paragraphs.length; i++) {
  let dataSetOne = paragraphs[i].getAttribute('x');
  dataSetOneArray.push(dataSetOne);
}

Though, you can achieve that in a more simpler way using Array.prototype.map():

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

var elList = Array.from(document.querySelectorAll('p'));
var res = elList.map(el => el.getAttribute('x'));
console.log(res);
<p x="30">Paragraph 1</p>
<p x="50">Paragraph 2</p>
<p x="100">Paragraph 3</p>

Upvotes: 1

Alex - Tin Le
Alex - Tin Le

Reputation: 2000

How about

let dataSetOneArray = [];
for (i = 0; i < paragraphs.length; i++) {
    let dataSetOne = paragraphs[i].getAttribute('x');
    dataSetOneArray.push(dataSetOne);
  }

Upvotes: 1

Related Questions