JavaScript and querySelector

后端 未结 4 568
情话喂你
情话喂你 2021-01-25 03:55

I have this HTML:

Intermediate steps

\"intermediate
相关标签:
4条回答
  • 2021-01-25 04:13

    Try this code

    document.querySelector('.staticStep :nth-child(i)').src = images[num][i];
    
    where i = 0,1,2,--- ,n.
    
    0 讨论(0)
  • 2021-01-25 04:14

    document.querySelector returns the first element within the document thus the error. you probalbly want to try: document.querySelectorAll

    var elements = document.querySelectorAll(".staticStep img");
    
    elements[0].src  =.....
    elements[1].src  =.....
    elements[2].src  =.....
    

    Or you could use jQuery instead.

    0 讨论(0)
  • 2021-01-25 04:20

    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/

    0 讨论(0)
  • 2021-01-25 04:37

    Try this to return all src:

    map = Function.prototype.call.bind([].map);
    map(document.querySelectorAll(".image"), function(o){
        return o.src;
    });
    

    or set src just with

    o.src="whatever";
    

    Here is the Fiddle.

    Look MDN for compatibility of map.

    0 讨论(0)
提交回复
热议问题