Checking Element Availability With Jquery

When we create a website by using or including Javascript sometimes we need to know whether an element is present or not on our web page, then we can apply the next action to it.

jquery-selectors

If we use pure Javascript, we usually use document.getElementById.

How about using it like this

if(document.getElementById(‘box’)){
// statements here
}
If we use Jquery it will be easier, because it will shorten the writing of the code.

But yes, it becomes a bit heavy because we have to include the Jquery script. So please choose whether to use Jquery or not.

If using Jquery then to check if an element exists or not like this.

if($(‘#box’)){
// statements here
}
But the problem with the code above is that the response will always be considered TRUE, even if the div doesn’t exist.

Therefore we recommend using .length, as follows

if($(‘#box’).length){
// statements here
}
Using the .length command, the return response is how many divs are in our document.
With .length then if the result is 0 then the response is False.

Okay, so a few tips this time.
Walla web design Indonesia.

Share To Social Media