I am building a simple chatbot. On each new message received from the server, a new HTML element is created and pushed to the browser.
So, for example, message 1 will be :
<div class="message-computer"><p>Hi, how are you?</p></div>
Then you (the user) types/sends a message, which shows up as :
<div class="message-user"><p>I am good, thanks!</p></div>
and so on and so forth.
I am trying to add a button to change the background color of all existing chat messages AND any new incoming messages from the computer.
This would work if I edited the CSS for .message-computer. I want to be able to switch between the two colours though.
So, I have added a button in my HTML, and it links to this javascript :
<script>
function changeClass(){
var myElements = document.querySelectorAll(".message-computer");
for (var i = 0; i < myElements.length; i++) {
myElements[i].style.color = "black";
myElements[i].style.backgroundColor = "yellow";
}
}
</script>
This kind of works - it injects the CSS into existing elements like so -
<div class="message-computer" style="color: black; background-color: yellow;"><p>Hi, how are you?</p></div>
It doesn't work for new messages at all though.
How can I make it work for any new and incoming messages? I have tried setting the parent element, but since a new div is created for every new element this does not work.
changeClass()?