[javascript] jQuery - how to check if an element exists?

I know that you can test for width() or height() but what if the element's display property is set to none? What other value is there to check to make sure the element exists?

This question is related to javascript jquery if-statement

The answer is


jQuery should be able to find even hidden elements. It also has the :visible and :hidden selectors to find both visible and hidden elements.

Does this help? Not sure without more info.


You can use the visible selector:

http://api.jquery.com/visible-selector/


Assuming you are trying to find if a div exists

$('div').length ? alert('div found') : alert('Div not found')

Check working example at http://jsfiddle.net/Qr86J/1/


I use this:

if ($('.div1').size() || $('.div2').size()) {
    console.log('ok');
}

Mostly, I prefer to use this syntax :

if ($('#MyId')!= null) {
    // dostuff
}

Even if this code is not commented, the functionality is obvious.


if ($("#MyId").length) { ... write some code here ...}

This from will automatically check for the presence of the element and will return true if an element exists.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to if-statement

How to use *ngIf else? SQL Server IF EXISTS THEN 1 ELSE 2 What is a good practice to check if an environmental variable exists or not? Using OR operator in a jquery if statement R multiple conditions in if statement Syntax for an If statement using a boolean How to have multiple conditions for one if statement in python Ifelse statement in R with multiple conditions If strings starts with in PowerShell Multiple conditions in an IF statement in Excel VBA