Rahul
Rahul

Reputation: 347

what is the difference between attributes[0] and attributes.item(0) in javascript dom?

I am beginner in javascript and came to know that we can use element.attributes[0] and element.attributes.item(0) to call the first attribute in html element. Is there any difference behind the scene ? If no, what is better to use ?

Upvotes: 2

Views: 551

Answers (2)

meskobalazs
meskobalazs

Reputation: 16051

They are interchangable. The array notation is a syntactic sugar, and it might be a bit misleading, because element.attributes is not an Array, but a NodeList, so the usual array methods do not work on it. I think, that the choice between them is up to personal preference.

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075815

There isn't one other than that item is a method call. The result is the same, other than that element.attributes[0] will give you undefined for an attribute that isn't present, but element.item(0) will give you null.

const ex = document.querySelector("span");
console.log(ex.attributes[0]);
console.log(ex.attributes.item(0));
<span>x</span>

Upvotes: 1

Related Questions