New to JS. All of the questions I could find with similar titles to mine were a bit too complicated for me to understand.
Simply put, I am trying to loop through an array and return one result at the end that essentially adds/concatenates all of the values of the array together.
However, I can't seem to get it to work, as the items in the array are blocks of HTML code, rather than simple strings or numbers. Here's a dumbed-down version.
HTML:
<article class="wrapper"><p>Some text 1.</p></article>
<article>No class.</article>
<article class="wrapper"><p>Some text 2.</p></article>
<article>No class.</article>
<article class="wrapper"><p>Some text 3.</p></article>
I am trying to figure out a way to end up with a template literal of this code:
<article class="wrapper"><p>Some text 1.</p></article>
<article class="wrapper"><p>Some text 2.</p></article>
<article class="wrapper"><p>Some text 3.</p></article>
So that I can inject the entire thing as the innerHTML of another element on a different page.
Started with this JS:
articleArray = document.querySelectorAll('.wrapper').outerHTML;
console.log(articleArray)
// This will return an array with the full HTML of the 3 "wrapper" articles as each item
Then tried to create a loop that will take the full HTML of item 1 on first loop and set it as something like an accumulator value. Then on second loop, it would take the full HTML of item 2 and concatenate it directly to item 1, and that would be the new accumulator value. And so on.
I have far more than 3 items for what I'm applying this to in real life, otherwise I could just do something like articleArray[0] + articleArray[1] + articleArray[2].
I tried a million things, but here were the closest attempts:
- Logging
var articleArray = document.querySelectorAll('.wrapper').outerHTML;
for (i = 0; i < searchWrappers.length; i++) {
searchWrapper = articleArray[i];
console.log(searchWrapper);
}
// Console log brought back 3 objects, but I need to combine them
- Concatenating
var articleArray = document.querySelectorAll('.wrapper').outerHTML;
var searchStr = ''
for (i = 0; i < articleArray.length; i++) {
itemHTML = articleArray[i];
fullString = searchStr += itemHTML;
console.log(fullString);
}
// This did concatenate the 3 items, but only as:
// [object HTMLElement][object HTMLElement][object HTMLElement]
// and not the actual HTML
- Concatenating and logging
const articleArray = document.querySelectorAll('.wrapper').outerHTML;
const sum = articleArray.reduce((accumulator, value) =>
$(accumulator).concat($(value)));
console.log(sum);
// This brought back a normal array of the 3 items again
Any help appreciated!
Edit: Thanks for all your responses! I am going to go through them now and testing your solutions on my real code to see what works best.