javascriptundefinedgetelementsbyname

Javascript Length Undefined or Zero


I am trying to write a Javascript function that returns a single element given the name. I found this question and modified the answer to use the ternary operator.

function getField(fieldName)
{
    var elements = document.getElementsByName(fieldName);

    return elements.length && elements.legth > 0 ? elements[0] : null;
}

My question is about the case where document.getElementsByName(fieldName) doesn't find any matches. Does it return undefined or 0? When I output elements.length as an alert message, the value in the alert is 0 but the console Chrome's DevTools says undefined. When I call console.log(elements.length) from the console, it ouputs 0 and undefined.

My tests in Chrome

I know that my function handles either case, but what am I missing here? What is Javascript actually doing?

Thanks in advance for helping me understand this.

EDIT: Sorry for posting a picture instead of actual code and thanks for the syntax clarification.


Solution

  • As your question seems to be what document.getElementsByName is returning when it isn't found, it would be an empty NodeList, with a length of 0 (so not undefined)

    Therefor, the easiest would be as dandavis suggested in his comment to simply return the first element of the nodelist. If it is empty, it will be undefined, if not it would the first element (not sure if that always matches your case though)

    so your function might as well be

    function getFieldAt(fieldName, index = 0) {
      return document.getElementsByName(fieldName)[index];
    }
    

    if you don't use optional parameters, you could change it to

    function getFieldAt(fieldName, index) {
      return document.getElementsByName(fieldName)[index || 0];
    }
    

    Your misunderstanding about the devtools are thoroughly explained in the comments and the other answer as well :)