javascript tutorial - [Solved-5 Solutions] Check if element exists in jQuery - javascript - java script - javascript array
Problem:
How to check if element exists in jQuery ?
Solution 1:
$('#elemId').length---^
click below button to copy the code. By JavaScript tutorial team
Solution 2:
if( $('#selector').length ) // use this if we are using id to check
{
// it exists
}
if( $('.selector').length ) // use this if we are using class to check
{
// it exists
click below button to copy the code. By JavaScript tutorial team
Solution 3:
if ($("#mydiv").length > 0){
// do something here
}
click below button to copy the code. By JavaScript tutorial team
Solution 4
if ($("#mydiv").length){ }
click below button to copy the code. By JavaScript tutorial team
Solution 5:
//we can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}
if(document.querySelector("#elemId")){}
//we can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}
jQuery:
if(jQuery("#elemId").length){}