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.
The
getElementByIdmethod returns an Element object that you can use to interact with the element. If the element is not found,nullis returned. In case of an input element, thevalueproperty of the object contains the string in the value attribute.By using the fact that the
&&operator short circuits, and that bothnulland 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: