When I want to check if an element exists in a page. Are these two checks the same? Is there a better more compact way to check the existence?
What if I want to check if the value == ''
. Can this be included in this check as well?
When I want to check if an element exists in a page. Are these two checks the same? Is there a better more compact way to check the existence?
What if I want to check if the value == ''
. Can this be included in this check as well?
A reference to an element will never look "falsy", so leaving off the explicit null check is safe.
Javascript will treat references to some values in a boolean context as false
: undefined, null, numeric zero and NaN
, and empty strings. But what getElementById
returns will either be an element reference, or null. Thus if the element is in the DOM, the return value will be an object reference, and all object references are true
in an if ()
test. If the element is not in the DOM, the return value would be null
, and null
is always false
in an if ()
test.
It's harmless to include the comparison, but personally I prefer to keep out bits of code that don't do anything because I figure every time my finger hits the keyboard I might be introducing a bug :)
Note that those using jQuery should not do this:
if ($('#something')) { /* ... */ }
because the jQuery function will always return something "truthy" — even if no element is found, jQuery returns an object reference. Instead:
if ($('#something').length) { /* ... */ }
edit — as to checking the value of an element, no, you can't do that at the same time as you're checking for the existence of the element itself directly with DOM methods. Again, most frameworks make that relatively simple and clean, as others have noted in their answers.
It's better (but wordier) to use:
var element = document.getElementById('something');
if (element != null && element.value == '') {
}
Please note, the first version of my answer was wrong:
var element = document.getElementById('something');
if (typeof element !== "undefined" && element.value == '') {
}
because getElementById()
always return an object (null object if not found) and checking for"undefined"
would never return a false
, as typeof null !== "undefined"
is still true
.
Just do it like this:
if(!document.getElementById("someId") { /Some code. Note the NOT (!) in the expresion/ };
If element with id "someId" does not exist expresion will return TRUE (NOT FALSE === TRUE) or !false === true;
try this code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="format-detection" content="telephone-no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, minimum-scale=1, maximum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi">
<title>Test</title>
</head>
<body>
<script>
var createPerson = function (name) {
var person;
if (!document.getElementById(name)) {
alert("Element does not exist. Let's create it.");
person = document.createElement("div");
//add argument name as the ID of the element
person.id = name;
//append element to the body of the document
document.body.appendChild(person);
} else {
alert("Element exists. Lets get it by ID!");
person = document.getElementById(name);
}
person.innerHTML = "HI THERE!";
};
//run the function.
createPerson("someid");
</script>
</body>
</html>
Try this in your browser and it should alert "Element does not exist. Let's create it."
Now add
<div id="someid"></div>
to the body of the page and try again. Voila! :)
document.getElementById('something') can be 'undefined'. Usually (thought not always) it's sufficient to do tests like if (document.getElementById('something'))
.
Yeah. Try this.. lazy evaluation should prohibit the second part of the condition from evaluating when the first part is false/null:
var someval = document.getElementById('something')
if (someval && someval.value <> '') {
jquery will provide you with this and more ...
if($("#something").val()){ //do stuff}
It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.
jQuery(document).ready(function() {
/* finds closest element with class divright/left and
makes all checkboxs inside that div class the same as selectAll...
*/
$("#selectAll").click(function() {
$(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
});
});
Cleanest version specially good if you just want to get the .value
from the element.
document.getElementById('elementsid') ? function_if_exists(); function_if_doesnt_exists();