34

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?

Philipp M
  • 1,877
  • 7
  • 27
  • 38
Malik Daud Ahmad Khokhar
  • 13,470
  • 24
  • 79
  • 81

7 Answers7

34

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • There is also a lot of good info in this post. (But I prefer to always check typeof by habit.) – Andir Jul 14 '10 at 14:50
  • 3
    Checking "typeof" in this case is completely useless because the return value from `getElementById` will always be type "object", even when it's null. – Pointy Jul 14 '10 at 15:10
  • 4
    For me, the whole point of jquery is that you would not need the "if". Just the jquery selector. – NimChimpsky Jul 14 '10 at 15:12
  • @batthink agreed - it's pretty rare that you need to check like that, but not outlandish. – Pointy Jul 14 '10 at 15:14
23

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.

worldofjr
  • 3,868
  • 8
  • 37
  • 49
Andir
  • 2,063
  • 1
  • 15
  • 22
  • 1
    There are many ways to check for definition. And many ways to break them. Say for instance you type (if (someValue) {}): What if someValue == false? It's defined, but it's false so the condition fails. If you use (if (someValue != undefined) {}): I can break your code by setting undefined = true. typeof always returns a type string and if the object you are testing is not defined, it returns "undefined"). – Andir Jul 14 '10 at 14:56
  • 1
    In this *specific* case, he's calling `getElementById()`. We *know* what that will return. It cannot return the constant `false`, for example. It will return an element, or `null`. – Pointy Jul 14 '10 at 15:04
  • Wow, setting undefined = true ... yikes. I'd sure like to know what the rationale was for that being allowed. Anyway, good explanation, thanks. – Tim Goodman Jul 14 '10 at 15:07
  • 1
    @Tim you can use `(void 0)` instead of `undefined` if you're paranoid. – Pointy Jul 14 '10 at 15:11
  • what happened if i just do `if (element)` – windmaomao Aug 28 '20 at 19:56
6

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! :)

Gawran
  • 61
  • 1
  • 2
2

document.getElementById('something') can be 'undefined'. Usually (thought not always) it's sufficient to do tests like if (document.getElementById('something')).

Robusto
  • 31,447
  • 8
  • 56
  • 77
1

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 <> '') {
Fosco
  • 38,138
  • 7
  • 87
  • 101
  • 2
    I would not recommend needlessly calling `getElementById` twice like that. – Pointy Jul 14 '10 at 14:45
  • No need to evaluate `document.getElementById('something')` twice. – Gumbo Jul 14 '10 at 14:46
  • He specifically asked to check that the value of the element not equal '', at least that is how I read his intent.. – Fosco Jul 14 '10 at 14:48
  • Yeah, in which case you store a the element you get back from the getElementById() call and use that instead of calling getElementById() twice. See my answer. – Andir Jul 14 '10 at 14:51
0

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);
    });
});
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
  • 7
    "Use JQuery" is worth an upvote all on its own? Not even "If you're using JQuery, you could do it this way..."? Man... Maybe I'd have more rep if I just posted "JQuery can do it" in every JavaScript thread. – Tim Goodman Jul 14 '10 at 15:03
  • lol. Good advice imho : use jquery for every javascript problem that is. – NimChimpsky Jul 14 '10 at 15:06
  • jQuery is "good advice" but it's not what was being asked. I love what jQuery provides and use it extensively. It's a great framework to get the hang of. – Andir Jul 14 '10 at 15:17
0

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();
Pedro Pereira
  • 480
  • 5
  • 12