Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading