Skip to content
Advertisement

How can I join different variables into one array?

I am trying to an array that look like this : let whatever= ["one,"two","three","four","five"] out of the divs below.

 <div class="randomClass">one</div>
 <div class="randomClass">two</div>
 <div class="randomClass">three</div>
 <div class="randomClass">four</div>
 <div class="randomClass">five</div>

How can it be done ? I’ve tried Array.form() / tried a few things with random.innerText . Nothing seems to work

Advertisement

Answer

This should do the trick

const elements = document.querySelectorAll('.randomClass') // get all Dom elements
const elementsArray =  Array.from(elements); // transform into iterable
const final = elementsArray.map(node => node.textContent) // map and get content

edit: use of Array.from instead of older version

Or as a one-line

Array.from(document.querySelectorAll('.randomClass')).map(node => node.textContent)
Advertisement