Reputation: 41
I want to create a loop that creates multiple divs that only changes these two variables which I would replace with the IDs from the array.
var ids = ['id1', 'id2', 'id3']
<div class="post" id={{ids[]}}">
<blockquote
class="instagram-media"
data-instgrm-permalink="https://www.instagram.com/p/{{ids[]}}
data-instgrm-version="13">
</blockquote>
</div>
Upvotes: 1
Views: 1145
Reputation: 20821
Loop through your array with Array.prototype.forEach() and generate a single string of html content.
I've used a helper function makePost
, but you could just do it in the body of the forEach callback.
Then update the DOM only once with the generated content using Element.insertAdjacentHTML() to avoid layout thrashing.
const ids = ["id1", "id2", "id3"];
const makePost = (id) => `
<div class="post" id="${id}">
<blockquote
class="instagram-media"
data-instgrm-permalink="https://www.instagram.com/p/${id}"
data-instgrm-version="13">
Content - ${id}
</blockquote>
</div>`;
let htmlContent = ''
ids.forEach(id => {
htmlContent += makePost(id)
})
const d1 = document.getElementById('dynamic-content');
d1.insertAdjacentHTML('beforeend', htmlContent);
<div id="dynamic-content"></div>
Upvotes: 2
Reputation: 31987
Loop through the array, create a string, insert the id
into the right positions using string literals and append this string to document.body.innerHTML
:
var ids = ['id1', 'id2', 'id3'];
ids.forEach(function(e) {
document.body.innerHTML += `
<div class="post" id=${e}">
<blockquote
class="instagram-media"
data-instgrm-permalink="https://www.instagram.com/p/${e}
data-instgrm-version="13">
</blockquote>
</div>
`
})
.post {
border: 1px solid;
}
Upvotes: 3