26

Related to this question here. Can I check if an element in the DOM has a value or not? I'm trying to put it into an 'if' statement and not sure if my approach is correct. Here goes:

if (document.getElementById('customx')){
    //do something
}

Or should it be:

if (document.getElementById('customx') == ""){
    //do something
}

EDIT: By value I mean, customx is a text input box. How can I check if this field has no text entered.

Community
  • 1
  • 1
zik
  • 2,835
  • 8
  • 40
  • 60

5 Answers5

41

The getElementById method returns an Element object that you can use to interact with the element. If the element is not found, null is returned. In case of an input element, the value property of the object contains the string in the value attribute.

By using the fact that the && operator short circuits, and that both null and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:

var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
  alert("My input has a value!");
}
Jonas Høgh
  • 9,858
  • 1
  • 23
  • 44
  • 1
    @simon Works fine on Chrome for me. Remember that you cannot access the elements of the document object until the DOMContentLoaded event has fired https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event – Jonas Høgh Jan 28 '20 at 09:46
  • thank you let me check out and I have problem I will going to tell you – simon Jan 30 '20 at 16:21
8

getElementById will return false if the element was not found in the DOM.

var el = document.getElementById("customx");
if (el !== null && el.value === "")
{
  //The element was found and the value is empty.
}
Dreendle
  • 151
  • 4
2
var input = document.getElementById("customx");

if (input && input.value) {
    alert(1);
}
else {
    alert (0);
}
0

Your first one was basically right. This, FYI, is bad. It does an equality check between a DOM node and a string:

if (document.getElementById('customx') == ""){

DOM nodes are actually their own type of JavaScript object. Thus this comparison would never work at all since it's doing an equality comparison on two distinctly different data types.

Mike Thomsen
  • 35,490
  • 10
  • 55
  • 80
0

You want:

if (document.getElementById('customx').value === ""){
    //do something
}

The value property will give you a string value and you need to compare that against an empty string.

Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264