Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array Elements Return undefined

it is a very simple html document with a js script.

...
<script type = "text/javascript"> src = "xxx.js"></script>
...

<body>
  <ul id ="pics">
    <li><a href="A.jpg">A</a></li>
    <li><a href="A.jpg">A</a></li>
    <li><a href="A.jpg">A</a></li>
  </ul>
</body>

the js file is:

var picspics = document.querySelectorAll("#pics ul > li > a");
alert(picspics[0]);

But it returned undefined, anyway, if just alert picspics, it will return "object nodelist", that sounds fine.

At first, I thought it is a dom loading problem, so I added

window.onload(){}

outside of my code, which also failed.

The all thing start with when I tried to use for loop to iterate all li > a elements and add a onclick event, which shows in chrome console that the array of the a element is undefined, so I tried to debug it with alert function.

After which, I tried to unattach the js file, just loaded the html in chrome, and than type the js code in the console, it also failed as expected which I suggest that is the same to the window.onload function.

Anyway, what is my fault here? Should not the picspics variable return an array contains 3 a element? Then how could the first element is undefined?

Thnx.

like image 615
Fadeoc Khaos Avatar asked Aug 25 '26 16:08

Fadeoc Khaos


2 Answers

The query you are providing is var picspics = document.querySelectorAll("#pics ul > li > a"); but pics is the ul. Change it to:

var picspics = document.querySelectorAll("ul#pics > li > a");
like image 169
Dom Avatar answered Aug 28 '26 06:08

Dom


The selector is wrong, it should be:

document.querySelectorAll("#pics > li > a");
like image 26
undefined Avatar answered Aug 28 '26 07:08

undefined