3

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.

2 Answers 2

2

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");
Sign up to request clarification or add additional context in comments.

2 Comments

thnx, I have not enough reputation to vote up, but thank you.
Anytime! Glad I could help! :)
1

The selector is wrong, it should be:

document.querySelectorAll("#pics > li > a");

1 Comment

thnx, I have not enough reputation to vote up, but thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.