When I want to check if an element exists in a page. Are these 2 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 somehow.
views:
86answers:
6document.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);
});
});
It's better (but wordier) to use:
var element = document.getElementById('something');
if (typeof element !== "undefined" && element.value == '') {
}
Edit: Added value == '' condition.
Edit2: I was corrected. getElementById() will indeed return an object, null or not. So a != null check will work where the above will not. Yet another reason to check your work. ;) Thanks.
var element = document.getElementById('something');
if (element != null && element.value == '') {
}
I use this,vide: What is the best way to check for an empty string in JavaScript?