Last Updated: February 25, 2016
·
2.207K
· LuRsT

Check if element exists in JQuery

if ( $("#element").length ){
    // do stuff
}

4 Responses
Add your response

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 ·