How to check if an element exists in HTML with jQuery


Recently a friend asked me how to run a function only if there is an determined element in HTML.

How can this be a common question, I decided to put on the blog.

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

With this if() you check if an element exists on the page, and if yes (true), run a code in particular. If the if() returns false, the code inside it will be ignored.