XenTerSeO XenTerSeO - 1 month ago 19
Javascript Question

How to combine values in the array?

I have the following html:

<div class="topics">
<span class="topic" data-value="hello">hello</span>
<span class="topic" data-value="world">world</span>
<span class="topic" data-value="one">one</span>
<span class="topic" data-value="two">two</span>
<span class="topic" data-value="six">six</span>
</div>


How to get value from each block and combine?
the result should be:

["hello", "world", "one", "two", "six"]

how can i achieve this ?

Answer

You'd get the spans and map back the text content

var text = [].map.call(document.querySelectorAll('.topics span'), function(elem) {
  return elem.textContent; // or elem.dataset.value for the data-attribute
});

console.log(text)
<div class="topics">
  <span class="topic" data-value="hello">hello</span>
  <span class="topic" data-value="world">world</span>
  <span class="topic" data-value="one">one</span>
  <span class="topic" data-value="two">two</span>
  <span class="topic" data-value="six">six</span>
</div>