-2

I have read about the difference between both: Difference between dot and bracket notation

However when I try to put together a simple HTML example using default JavaScript .length to refer to them:

<ul id="allList">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
  <li>e</li>
  <li>f</li>
</ul>

console.log(document.getElementById("allList").getElementsByTagName("li").length);
//6


console.log(document.getElementById("allList").getElementsByTagName("li")[length]); 
//<li>a</li> 

Using dot notation is giving me 6 because it registers total of 6 arrays from the HTML but when comes to bracket, why is it giving me the first html list instead?

Working example here: sample code

Updates: Ok I just found out that I have missed out the quotes. It should be ["length"] instead of [length]. Question solved.

albert
  • 8,285
  • 3
  • 19
  • 32
Vincent1989
  • 1,593
  • 2
  • 13
  • 25
  • Do you have any variable with the name `length` defined in that scope? – thefourtheye Jul 11 '16 at 09:13
  • 1
    I guess you should use `['length']` instead of `[length]` – Vladimir G. Jul 11 '16 at 09:15
  • Yes that, I have missed out the quotes. – Vincent1989 Jul 11 '16 at 09:17
  • @thefourtheye — Yes: https://developer.mozilla.org/en-US/docs/Web/API/Window/length – Quentin Jul 11 '16 at 09:18
  • "I just found out that I have missed out the quotes" — Three answers said that already. Please read [How does accepting an answer work?](http://meta.stackoverflow.com/questions/5234/how-does-accepting-an-answer-work) – Quentin Jul 11 '16 at 09:20
  • @Quention I have read it before, as soon as I finish posting and some heads up from others I immediately saw that is a another silly mistake from my end. I know it is too late to delete the question now and people will start downvoting regardless whether is a silly mistake or not. I'm just trying my best not to get anymore downvotes....At the end of the day who doesn't make careless mistake..... – Vincent1989 Jul 11 '16 at 09:58

3 Answers3

1

Try putting 'length' in the brackets instead of length

Basically you try to access an object property. Here the object is an array but it works for other objects. You can access the property using ".propertyName" or using brackets with ['popertyName']

R. Foubert
  • 633
  • 4
  • 8
1

Square bracket notation takes a string. length is a variable. Since you haven't explicitly set it, it is window.length which is the number of frames in the document (which must be 0 since you are getting the first element in the node list).

If you want to access the length property then say ["length"] and actually pass a string.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

[] this means fetching element from an array. Seems like your 'length' variable is defined somewhere with 0 value, that's why it gives you first elem of 'li' array.

  • "element from an array" — Property from any kind of object. In this case, it is an HTMLCollection, not an array. – Quentin Jul 11 '16 at 09:21