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.

>Solution :

Quite trivial

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

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>

Leave a Reply