Yogesh Chauhan's Blog

How to check if the element exists using JavaScript and jQuery?

in JavaScript & jQuery on September 11, 2020

Using jQuery

We can make use of jQuery ID Selector

The syntax is like:


$('#elementId')

The ID selector selects a single element with the specified id which is same as JavaScript’s document.getElementById().


if ($('#elementId').length > 0) {
  // element exists.
}

Using JavaScript

We can use the same ID selector but from pure JavaScript.

Once we have that we can try to see if it’s not undefined or null.


var el =  document.getElementById('elementId');

if (typeof(el) != 'undefined' && el != null)
{
  // element exists.
}

Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
How to create a Recent Posts function in WordPress?WordPressThe difference between isFinite() method and isFinite() function in JavaScriptJavaScriptfirst-of-type and last-of-type selectors in CSSCSSHow to change CSS with jQuery?CSSVariables scope and shadowing in SCSS (Sass)SCSSHow to check if the page is the home page in WordPress?WordPressModules and its Core features in JavaScriptJavaScriptHow to Use ROLLUP Operator in SQL and MySQL?SQL/MySQL@forward rule in SCSS (Sass)SCSSContainers 101: What are containers?MiscellaneousPagination in CSS with multiple examplesCSSHow to Sort (Shuffle) an Array in Random Order in JavaScript?JavaScript