High Tekk
High Tekk

Reputation: 11

Getting content of span element

I have initial empty array named array. In my page I have several span elements with class "inbox". I need to get this collection of span elements and then collect their content into another array. But this line of code array[i] = values1[i].innerHTML shows error Cannot read properties of undefined (reading 'innerHTML') at HTMLButtonElement.btn.onclick. I can't get it.

btn.onclick = function() {
        var values = document.getElementsByClassName("inbox")
        var values1 = Array.prototype.slice.call(values);
         
         for (i = 0; i<arrOfWords.length; i++) {
              array[i] = values1[i].innerHTML
          }
         console.log(array)
     }

Upvotes: 0

Views: 50

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28196

Maybe this is what you are looking for?

document.querySelector("button").onclick = function() {
  const array=[...document.getElementsByClassName("inbox")].map(el=>el.textContent);
  
  // or, if you prefer pre-ES6 notation:
  const arr=[].map.call(document.getElementsByClassName("inbox"),el=>el.textContent);
  
  console.log(array);
  console.log(arr)
}
<span class="inbox">one</span> extra text
<span class="inbox">two</span>
<span class="inbox">three</span>
<span class="inbox">four</span> not to
<span class="inbox">five</span>
<span class="inbox">six</span>
<span class="inbox">seven</span> be collected
<span class="inbox">eight</span>
<span class="inbox">nine</span>
<span class="inbox">ten</span>

<button>go</button>

Upvotes: 1

Related Questions