Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VanillaJS: grab the text from multiple elements (same class) and list in separate div

I'm trying to get the text content of a specific class across the page, then print them out in a different div, separated by a comma.

Example:

<!-- Within the HTML Page -->
<div class="copyright">Image one</div>
<div class="copyright">Image two</div>
<div class="copyright">Image three</div>

<!-- Should output: "Image one, Image two, Image three" -->
<div class="showCopyright"></div> 

How would I achieve this using only pure VanillaJS, not jQuery?

Would I use the innerHTML? or innerText?

I really appreciate any help you can provide.

like image 492
Tudor Avatar asked Nov 19 '25 15:11

Tudor


1 Answers

I would use textContent unless there is or you want markup in the result

window.addEventListener("DOMContentLoaded", () => { 

  document.querySelector(".showCopyright")
    .textContent = [...document.querySelectorAll(".copyright")]
      .map(({ textContent }) => textContent.trim()).join(", ");

});      
<!-- Within the HTML Page -->
<div class="copyright">Image one</div>
<div class="copyright">Image two</div>
<div class="copyright">Image three</div>

<!-- Should output: "Image one, Image two, Image three" -->
<div class="showCopyright"></div>
like image 105
mplungjan Avatar answered Nov 21 '25 05:11

mplungjan