Tân Nguyễn Tân Nguyễn - 9 days ago 7
Javascript Question

Object reference in jquery

I have a small example:



let length = $('body > p').length;
console.log(length);

$('body').append($('<p>').text('plain text'));
console.log(length);

setTimeout(() => console.log(length), 1000)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>





My question: after appending, why wouldn't
length
update new value (
1
)? I've tried to delay 1 second before logging, but same result. Why?

Answer

In JavaScript, variables are not re-evaluated whenever you call them. In your case, you set the value of length to 0 at the start of your script, and it will remain equal to 0 as long as you don't set it to another value with length = .... So to make your example work, you would need to do:

var length = $('body > p').length;
console.log(length);

$('body').append($('<p>').text('plain text'));
length = $('body > p').length;
console.log(length);