Home > OS >  Getting content of span element
Getting content of span element

Time:03-05

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)
     }

CodePudding user response:

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 >one</span> extra text
<span >two</span>
<span >three</span>
<span >four</span> not to
<span >five</span>
<span >six</span>
<span >seven</span> be collected
<span >eight</span>
<span >nine</span>
<span >ten</span>

<button>go</button>

  • Related