Jesse Lim Jia Nian Jesse Lim Jia Nian - 1 month ago 9
jQuery Question

How do I creates arrays from a series of <span>

How do I make an array from a series of

<span>
in a specific
<div>
when clicking
btn
?

<div class="btn">Make Arrays<div>

<div class="Wrapper">
<div class="some elements"></div>
<div class="Arrays">
<input type="text" placeholder="enter value">
<div>some stuff</div>
<span>123.23</span>
<span>52</span>
<span>728.4</span>
<span>52</span>
</div>
</div>
<div class="Wrapper">
<div class="some elements"></div>
<div class="Arrays">
<input type="text" placeholder="enter value">
<div>some stuff</div>
<span>10.8</span>
<span>28.7</span>
</div>
</div> ...


Output
var Array1 = ['123.23', '52', '728.4', '52']

var Array2 = ['10.8', '28.1']
...

The thing is, I will not know how many
class="Arrays"
will be because it is a dynamic elements. so maybe there should be a way of indexing it by adding dummy classes like 'Array1', 'Array2' into 'class="Arrays"'

So, basically, how do I index each
<Arrays>
div and make an array out of its
<span>


Many Thanks~~~ =)

Answer Source

That will return array of arrays.

function getArray() {
  const arr = Array.from(document.querySelectorAll('.Arrays'))
    .map(a => Array.from(a.querySelectorAll('span')).map(span => span.textContent));

  console.log(arr)
}
<button onclick="getArray()">getArray</button>

<div class="btn">Make Arrays
  <div>

    <div class="Wrapper">
      <div class="some elements"></div>
      <div class="Arrays">
        <input type="text" placeholder="enter value">
        <div>some stuff</div>
        <span>123.23</span>
        <span>52</span>
        <span>728.4</span>
        <span>52</span>
      </div>
    </div>
    <div class="Wrapper">
      <div class="some elements"></div>
      <div class="Arrays">
        <input type="text" placeholder="enter value">
        <div>some stuff</div>
        <span>10.8</span>
        <span>28.7</span>
      </div>
    </div>