tbriggs707
tbriggs707

Reputation: 99

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.

Upvotes: 0

Views: 2770

Answers (3)

Mister Jojo
Mister Jojo

Reputation: 22265

no need to test length value simply use:

function getField(fieldName)
{
  let elements = document.getElementsByName(fieldName);
  return (elements[0]) ? elements[0] : null;
}

console.log( getField('div-A') );
console.log( getField('neverExist') );
<div name="div-A"> div-A 1 </div>
<div name="div-A"> div-A 2 </div>
<div name="div-A"> div-A 3 </div>

Upvotes: 1

Icepickle
Icepickle

Reputation: 12796

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

Upvotes: 1

Nino Filiu
Nino Filiu

Reputation: 18483

elements.length is equal to 0 in your case.

Your understanding of console.log is misleading:

console.log(elements.length);
> elements.length is printed. It evaluates to 0, so 0 is printed
> console.log(elements.length). It evaluates to undefined, so undefined is printed.

Upvotes: 1

Related Questions