SCENARIO:
I am new to jQuery and I want to know if a certain DOM element exists in the page. I tried the snippet below but it didn't work.
if($("#myElementID")){
alert("The element exists!");
}
alert("The element exists!");
}
SOLUTION:
As a beginner, you might think that wrapping the jQuery selector inside an if statement will fix your problem. Ideally that code must work in ordinary programming aspect/concept.
The jQuery selector returns an object every time you use it. If we will use the above snippet, the selector will always return true - regardless if the element doesn't exists.
Here are the proper ways on how to determine if an element really exists in the page:
1. Use length property. This property returns the size of the object.
if($("#myElementID").length > 0){
alert("The element exists!");
}
or
if($("#myElementID").length){
alert("The element exists!");
}
TIP: It would be better to use the first implementation for the purpose of code readability.
As a beginner, you might think that wrapping the jQuery selector inside an if statement will fix your problem. Ideally that code must work in ordinary programming aspect/concept.
The jQuery selector returns an object every time you use it. If we will use the above snippet, the selector will always return true - regardless if the element doesn't exists.
Here are the proper ways on how to determine if an element really exists in the page:
1. Use length property. This property returns the size of the object.
if($("#myElementID").length > 0){
alert("The element exists!");
}
or
if($("#myElementID").length){
alert("The element exists!");
}
TIP: It would be better to use the first implementation for the purpose of code readability.
2. Use size() function.
if($("#myElementID").size()){
alert("The element exists!");
}
Hope it helps. Cheers!!!
if($("#myElementID").size()){
alert("The element exists!");
}
Hope it helps. Cheers!!!