I am building an HTML/CSS/Javascript application that dynamically embeds facebook posts based on an API that returns a list of facebook post ID’s. I loop through the post ID’s, generate an embed code with postId inserted for each post, and append to the DOM. Simple stuff.
However I need to append some simple text above each post, and I cannot figure out how to do this dynamically in Javascript. When I dynamically create the text and try to append it to the ID tag of each post, nothing seems to happen. I know the facebook embed code is generating a ton of code, so perhaps it’s getting overwritten. Is there any way to achieve this? See below for my code.
// Array of facebook post ID's
facebookArr = [{
post_id: "pfbid0cm7x6wS3jCgFK5hdFadprTDMqx1oYr6m1o8CC93AxoE1Z3Fjodpmri7y2Qf1VgURl"
},
{
post_id: "pfbid0azgTbbrM5bTYFEzVAjkVoa4vwc5Fr3Ewt8ej8LVS1hMzPquktzQFFXfUrFedLyTql"
},
];
// Variables to store post ID, embed code, parent container
let postId = "";
let embedCode = "";
let facebookContainer = document.getElementById("facebook-feed-container");
$(facebookContainer).empty();
// Loop through data to display posts
facebookArr.forEach((post) => {
postId = post.post_id;
postLink = `${postId}/?utm_source=ig_embed&utm_campaign=loading`;
embedCode = `<iframe src="https://www.facebook.com/plugins/post.php?href=https%3A%2F%2Fwww.facebook.com%2FIconicCool%2Fposts%2F${postId}&show_text=true&width=500" width="200" height="389" style="border:none;overflow:hidden" scrolling="no" frameborder="0" allowfullscreen="true" allow="autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share" id=fb-post__${postId}></iframe>`;
// Update the DOM
facebookContainer.innerHTML += embedCode;
});
facebookArr.forEach((post) => {
let additionalText = document.createElement("div");
additionalText.innerText = "additional text to append";
let postContainer = document.getElementById(`fb-post__${postId}`)
postContainer.append(additionalText)
});
#facebook-feed-container {
display: flex;
flex-direction: row;
row-gap: 1rem;
column-gap: 3rem;
padding: 1rem;
}
// Jquery script
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
// Parent container for posts
<div id="facebook-feed-container"></div>