JavaScript / jQuery always has the latest element or version of that element?
I am writing a usercript that grabs an element with something like:
var theElement = $('div.someClass:last');
To grab the last element in the class .someClass
, I can parse it.
This brings up my question. There is another script on this page dynamically adding a new <div class="someClass">
one every time. I want to always have the last element on the page with the selected class .someClass
.
Will Javascript / jQuery always have the last element or will I have to manually "update" it?
source to share
Sushant'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 should be done as $ (selector) is a rather expensive operation.
edit - only for ie9 and up, although http://caniuse.com/getelementsbyclassname
source to share
Not. It won't automatically update.
Every time you change something directly to the selector it is a good idea to cache it again.
The selector you want is not a live Node.
In such cases, if there is any change to the selector, I prefer not to cache at all in the first case.
So that I can use the selector directly and not the cached one.
source to share