简体   繁体   中英

Set src attribute of an html collection(img) from an array of paths as values to set on each img using ES6 pure Javascript?

I have an array of src values like [path1, path2, path3] and an html collection the same array length as arr value. So I want to pass each value to set src of the html elements. How can I do? I tried forEach, for Of, map, but it still either all elements in the same path or just one (the first element) setted.

//My code now
<img alt='first-in-collection'>
<img alt='second-in-collection'>
<img alt='third-in-collection'> 
//The variable
let arr = ['path1', 'path2', 'path3']
//Expected result 
<img src='path1' alt='first-in-collection'>
<img src='path2' alt='second-in-collection'>
<img src='path3' alt='third-in-collection'>

My Running Code Link

You don't need to run loops on both image and path arrays. Run the loop on any one array. Keep incrementing the iterator count and set the src of current iterator indexed image.

 let arr = ['path1', 'path2', 'path3'];\ // get all images let img = document.getElementsByClassName('img-thumbnail') // initialize iterator with 0 let i=0; for(let el of arr){ // set attribute of corresponding image img[i++].setAttribute('src', el) }
 <div class="col-8"> <div class="row produit-desc-lense"> <div class="col-4 text-center border-bottom"> <img class="img-fluid rounded img-thumbnail" alt="/"> <h5>caméra 2</h5> </div> <div class="col-4 d-flex align-items-center justify-content-center border-bottom"> <p></p> </div> <div class="col-4 d-flex align-items-center justify-content-center border-bottom"> <select id="selectNumber"> <option>Choose a number</option> </select> </div> </div><div class="row produit-desc-lense"> <div class="col-4 text-center border-bottom"> <img class="img-fluid rounded img-thumbnail" alt="/"> <h5>caméra 2</h5> </div> <div class="col-4 d-flex align-items-center justify-content-center border-bottom"> <p></p> </div> <div class="col-4 d-flex align-items-center justify-content-center border-bottom"> <select id="selectNumber"> <option>Choose a number</option> </select> </div> </div><div class="row produit-desc-lense"> <div class="col-4 text-center border-bottom"> <img class="img-fluid rounded img-thumbnail" alt="/"> <h5>caméra 2</h5> </div> <div class="col-4 d-flex align-items-center justify-content-center border-bottom"> <p></p> </div> <div class="col-4 d-flex align-items-center justify-content-center border-bottom"> <select id="selectNumber"> <option>Choose a number</option> </select> </div> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM