How can I check the existence of an element in jQuery?
The current code that I have is this:
if ($(selector).length > 0) {
// Do something
}
<
No need for jQuery (basic solution)
if(document.querySelector('.a-class')) {
// do something
}
Much more performant option below(notice lack of a dot before a-class).
if(document.getElementsByClassName('a-class')[0]) {
// do something
}
querySelector uses a proper matching engine like $() (sizzle) in jQuery and uses more computing power but in 99% cases will do just fine. The second option is more explicit and tells the code exactly what to do. It's much faster according to jsperf https://jsperf.com/getelementsbyclassname-vs-queryselectorall/25