Tân Nguyễn Tân Nguyễn - 1 year ago 97
Javascript Question

Object reference in jquery

I have a small example:

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

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

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
update new value (
)? I've tried to delay 1 second before logging, but same result. Why?

Answer Source

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;

$('body').append($('<p>').text('plain text'));
length = $('body > p').length;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download