JavaScript: Specific element exist or variable defined/undefined

From The Travis van der Font Wiki
Jump to: navigation, search
if (document.getElementById('example_element') !== null)
{
    var element_value = document.getElementById('example_element').value;
}

// if (element === null) alert('does not exist!');

Using jQuery

if ($('#example_element').length > 0) 
{ 
    var element_value = $('#example_element').val();
}

// if ($('#example_element').length === 0) alert('does not exist!');
Checking variables? Look for undefined:
if (var_name !== undefined) {...}
For older browser support (recommended):
if (typeof var_name !== 'undefined') {...}
Avoid using if(var_name === null) as it will throw a "ReferenceError: var_name is not defined" error Alternatively, you can check if a function exists
typeof functionExampleName === 'function'; // true

function functionExampleName(a, b, c) {}