4

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?

5
  • 1
    No, there isn't, since everything in JS is passed by value. Instead you could use an object with getter/setter properties. Commented Feb 1, 2015 at 14:54
  • Hey Teemu, can you provide an example of such an object? Commented Feb 1, 2015 at 15:20
  • 1
    At this post there's a setter, a getter would be just a function returning document.getElementById('messsages').textContent in your case. Commented Feb 1, 2015 at 15:29
  • 1
    So basically if I paste the following in my code, then 'convo' will always equal to the current value of the div 'messsages' which contains dynamic content? : var convo = { set title(text) { document.getElementById('messsages').textContent = document.title = text; } }; Commented Feb 1, 2015 at 17:05
  • @StackOverQuestions Ofcourse not, you've to apply your own code to the setter structure. The linked page shows a concept of setter only, it's not a direct answer to your question. Commented Feb 1, 2015 at 19:01

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Hey it didn't work, I get the error in the console "convo is not defined".
@StackOverQuestions If possible , can post pieces tried at OP ? , create stacksnippets , jsfiddle to demonstrate ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.