Tuesday, November 6, 2012

How To Determine If an Element Exists Using jQuery


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!");
}



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.

2. Use size() function.


if($("#myElementID").size()){
    alert("The element exists!");
}




Hope it helps. Cheers!!!





Thursday, June 14, 2012

How THIS Blog Works? (An Overview)

Basically, this blog is just like a reference for web developers. You might be wandering how does it work? Well, think of a Q&A page - but in this blog call it S&S(Scenario&Solution).

Every post has its own SCENARIO or problem (i.e. based on my actual programming experience) from which you may acquire the solution.

Example:
SCENARIO: I want to blah blah blah...

SOLUTION: To solve this kind of problem, blah blah blah...

You might also encounter TIP, NOTE or REMINDER that might help you to solve your problem.

You may now start seeking! ^_^

Wednesday, June 13, 2012

Why Did I Create THIS?

Whenever I code, I always encounter new challenges and new ideas. Each time I learned something new, I refuse to just keep it on my mind and my own sake. I want to share what I learned that's why I came up with this blog - even though I'm not that good in English grammar :D. Hopefully I can help! Let's start the ball rolling!