Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript/jQuery always have the latest element or version of that element?

I am writing a userscript that grabs an element with something like:

var theElement = $('div.someClass:last');

To grab the last element in the class .someClass so I can parse it.

This is where my question comes in. There is another script on this page dynamically adding a new <div class="someClass"> every once in a while. I want to always have the last element on the page with a class of .someClass selected.

Will Javascript/jQuery always have the latest element or will I have to manually "refresh" it?

like image 259
Seth Avatar asked Feb 27 '26 21:02

Seth


2 Answers

Sushanth's answer is correct, but according to this article you could use

var theElements = document.getElementsByClassName('someClass');

and then reliably use

var theElement = $(theElements[theElements.length - 1]); // wrapping in $() is optional

which is worth doing as $(selector) is quite an expensive operation to perform.

edit - only for ie9 and above though http://caniuse.com/getelementsbyclassname

like image 118
wheresrhys Avatar answered Mar 01 '26 12:03

wheresrhys


Your selector is evaluated and the result is returned. If you want to do what you're asking, you'll have to re-evaluate that selector.

like image 20
Steve H. Avatar answered Mar 01 '26 11:03

Steve H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!