Nikhil Utane
Nikhil Utane

Reputation: 1221

Need help to add javascript array contents to an existing piece of HTML code

My front-end skills are fairly limited. I have a trained language model which generates 'tweets'. I have this javascript function which currently displays the tweets as a paragraph.

function addResponse(msg) {
    document.getElementById("results").textContent = ""
    var para = document.createElement("div");
    var s = "<div class='center' id='gpt2'> <b> Here what our BOT has to say... </b> </br></br>"

     i = 1
     for (var key in msg){
         var value = msg[key];
         console.log(value);
         s = s + i + ") " + " <b>" + value + "</b> </br></br>"
         i = i + 1
     }
    para.innerHTML = s + "</div>";
    document.getElementById('append').appendChild(para);
  }

Instead of displaying in a paragraph, I want to display as a proper tweet. Here is a tailwind CSS implementation to create the UI of the tweet: https://codepen.io/webcrunchblog/pen/xedQVv

Currently this displays a fixed string "Starhopper". What I want to do is, loop through my array object 'msg' and display all the tweets with the proper UI .

Currently the addResponse() is called as part of ajax callback for successful response. From there how can I include the tailwind CSS code so that I can display every array element in its own tweet UI? Hope the question is clear.

EDIT: Created this codepen if anyone wants to try it out: https://codepen.io/nikhilno1/pen/RwPBWvb In the output, there is a tweet and three sentences. I want 3 tweets to be created for each of the sentence.

Upvotes: 0

Views: 47

Answers (1)

Rishabh Saxena
Rishabh Saxena

Reputation: 91

I've updated a bit of your code here: https://codepen.io/rxna/pen/OJVwMOm

The idea is to:

Clone the tweet element, have added a custom class for that:
var articleNode = document.querySelector(".tweet-body"); var clone = articleNode.cloneNode(true);

Update the text within each element:
var title = clone.querySelector(".tweet-text"); title.innerText = value;

And lastly append within the DOM:
document.getElementById("append").appendChild(clone);

It's not perfect but hopefully you'd get the idea.

Upvotes: 1

Related Questions