Michael J Caboose
Michael J Caboose

Reputation: 191

getElementsByClassName returns duplicate elements

Looking more for an explanation rather than solving a problem. I return 4 items from:

var inputFields = document.getElementsByClassName("calc-input-url");

but when I log the array as output I get this:

[
    input#tippedEmployees.form-control.calc-input-url,
    input#hourlyWage.form-control.calc-input-url, 
    input#weeklyTips.form-control.calc-input-url, 
    input#hoursTippedEmp.form-control.calc-input-url, 
    tippedEmployees: input#tippedEmployees.form-control.calc-input-url,
    hourlyWage: input#hourlyWage.form-control.calc-input-url, 
    weeklyTips: input#weeklyTips.form-control.calc-input-url, 
    hoursTippedEmp: input#hoursTippedEmp.form-control.calc-input-url, 
    item: function…
]

I then logged the length of the array to double-check and only got a return value of 4.

Where do these extra elements in the array come from, and why are they there/how can I make use of them (if at all)?

Upvotes: 1

Views: 1231

Answers (1)

deceze
deceze

Reputation: 522110

What you see there is not a regular array, but an HTMLCollection. The fact that the array "has keys" (tippedEmployees:) should be a giveaway that this is no ordinary array. The HTMLCollection exposes the elements in an array-like manner, but also directly via their ids. This is a convenience for you.

In practice there should be no problems, since you're either going to iterate the "array part" of it using for (var i = 0; i < list.length; i++) list[i]..., or you're going to access the elements directly by id.

Upvotes: 1

Related Questions