Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
526 views
in Technique[技术] by (71.8m points)

dom - JavaScript and querySelector

I have this HTML:

<div id="allSteps">
  <h3>Intermediate steps</h3>
  <span class="staticStep">→ <img src="" alt="intermediate step" class="image" ></span>
  <span class="staticStep">→ <img src="" alt="intermediate step" class="image"></span>
  <span class="staticStep">→ <img src="" alt="intermediate step" class="image"></span>
</div>

In javaScript, how do I access the .src for each image?

I tried the following but it gives me an error:

document.querySelector(".staticStep img").src[0] = images[num][0];
document.querySelector(".staticStep img").src[1] = images[num][1];
document.querySelector(".staticStep img").src[2] = images[num][2];

I also tried the following but it gives me a an error:

document.querySelector(".staticStep img")[0].src = images[num][0];
document.querySelector(".staticStep img")[1].src = images[num][1];
document.querySelector(".staticStep img")[2].src = images[num][2];

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try using document.querySelectorAll which returns all of the possible results instead of just the first one. The error you're getting (Uncaught TypeError: Cannot set property 'src' of undefined) is because querySelector only returns the first element found, not an array (and elements can't be accessed like arrays).

jQuery (the inspiration for querySelector and querySelectorAll) always allows you to access like an array ($('.staticStep img')[0] works), so this is probably where your confusion stems from.

Quick JSFiddle example: http://jsfiddle.net/j8ZUJ/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...