Check if element exists in JQuery
if ( $("#element").length ){
// do stuff
}
Written by LuRsT
Related protips
4 Responses
You can even omit the > 0
part - it's enough to check that the value is non-zero.
over 1 year ago
·
Oh yes, of course, thanks for the heads up :D
over 1 year ago
·
Not so quick. I mean jQuery DOM operations are slow. Maybe it's a quicker way:
document.querySelector('#element')
it return null if it's not exist, so it's false, otherwise it returns with the element, so it's true. It stops crawling on the 1st hit, jQuery does not (with big DOM it would be a problem on frequently search)
It's a not a big deal, but if you check a lot of elements then it's maybe painful.
Can I use? http://caniuse.com/#feat=queryselector
over 1 year ago
·
Thanks for you suggestion yitsushi, that does seem like the best option for this :D
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Jquery
Authors
Related Tags
#jquery
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#