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 >Image one</div>
<div >Image two</div>
<div >Image three</div>
<!-- Should output: "Image one, Image two, Image three" -->
<div ></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.
CodePudding user response:
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 >Image one</div>
<div >Image two</div>
<div >Image three</div>
<!-- Should output: "Image one, Image two, Image three" -->
<div ></div>
CodePudding user response:
Here is a pure javascript method to do that:
var textArray = [];
var elements = document.getElementsByClassName("copyright");
for (var i = 0; i < elements.length; i ) {
textArray.push(elements[i].innerText);
}
document.getElementsByClassName("showCopyright")[0].innerText = textArray.join(', ');
<div >Image one</div>
<div >Image two</div>
<div >Image three</div>
<div ></div>