Reputation: 283
I set the following in my console:
document.getElementById('messsages').textContent;
which gave me the output "this is a message i sent through websocket chat!"
I then did
var convo = document.getElementById('messsages').textContent;
and typed in convo
into the console and it gave me the same output as before. I then sent another message through my websocket chat and typed in convo and it gave me the old output but when I typed in document.getElementById('messsages').textContent;
it gave me the new output.
Why is this? And is there a method for me to assign a variable which updates its value accordingly with my element?
Upvotes: 4
Views: 111
Reputation: 1
Try utilizing an IIFE
var convo = function convo() {
return (function(elem) {
return elem.textContent
}(document.getElementById("messages"))
};
See also MutationObserver
setInterval(function() {
var arr = "abcdefg".split("");
var i = 1 + Math.floor(Math.random() * arr.length -1);
document.getElementById("messages").textContent = arr[i];
}, 2000);
var convo = function convo() {
return (function(elem) {
return elem.textContent
}(document.getElementById("messages")))
};
document.addEventListener("click", function() {
console.log(convo())
});
click
<div id="messages"></div>
Upvotes: 3