dpbikq
Last Updated: February 25, 2016
·
956
· LuRsT
43d7035caeafc49de5d7568cbf73175e

Check if element exists in JQuery

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

4 Responses
Add your response

4793
D42a7264714dee5006b9c99d2567a320

You can even omit the > 0 part - it's enough to check that the value is non-zero.

over 1 year ago ·
4798
43d7035caeafc49de5d7568cbf73175e

Oh yes, of course, thanks for the heads up :D

over 1 year ago ·
23935
Img 20150424 132017

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 ·
23937
43d7035caeafc49de5d7568cbf73175e

Thanks for you suggestion yitsushi, that does seem like the best option for this :D

over 1 year ago ·