Skip to content
Advertisement

write get.ElementByClass() from nested div to file

I’m working on a chatbot where users can talk to the chatbot and I would like to have the conversation logged into a text file. I was thinking grabbing the <div class="msg-text">, which represent the conversation the document.getElementByClass("msg-text")[0].innerText; which is the chatbot’s response and the document.getElementByClass("msg-text")[1].innerText; which is the user’s response and have it to be read into a file. The chatbot response in even numbers (0,2,4,6,8, etc.) and the odd number (1,3,5,7,9, etc.) is the user’s response.

Is there a more efficient way to grab the elements and have them written to a file? At this moment I get nothing in my file.

JavaScript
JavaScript

Advertisement

Answer

Yeah, don’t call document.getElementsByClassName() multiple times. Also, what happens if the user types in something twice before the chatbot responds?

I would recommend you add a msg-bubble-user and msg-bubble-bot to your .msg-bubble element. Then loop through them, recording the transcript according to the class name, not the position:

JavaScript

^untested

If your file is empty, add a console.log() call to see if you’re getting the text you’re expecting.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement