简体   繁体   中英

run JavaScript x amount times, each time number in array increase by 1

this is the html, which I cannot directly change the DOM, but able to modify things like attribute and class only with JS:

<div class="parent">
    <label class="child" for="label_1">
        <img src="/site/images/someimage.jpg">
    </label>
</div>
<div class="parent">
    <label class="child" for="label_2">
        <img src="/site/images/someotherimage.jpg">
    </label>
</div>
<div class="parent">
    <label class="child" for="label_3">
        <img src="/site/images/somedifferentimage.jpg">
    </label>
</div>

trying to use JS to replace the img src , so the src name will match the parent for attribute value, like

<div class="parent">
    <label class="child" for="label_1">
        <img src="/site/images/label_1.jpg">
    </label>
</div>
<div class="parent">
    <label class="child" for="label_2">
        <img src="/site/images/label_2.jpg">
    </label>
</div>
<div class="parent">
    <label class="child" for="label_3">
        <img src="/site/images/label_3.jpg">
    </label>
</div>

I have this:

<script>
let n = ""
let amt = document.getElementsByClassName("layout-choice-thumbnail-label").length;
for (let i = 0; i <= amt; i++) {
    n += i + ', ';
}

var attr = document.getElementsByClassName("child")[0].getAttribute("for");
var imgSrc = '../images/content/pagebuilder/' + cardId + '.jpg';
document.querySelectorAll(".child")[0].firstElementChild.setAttribute('src', imgSrc);
</script>

which only works for one, how could I change it so every time the page loads, the value inside the [0] is increased by 1, or when the whole script loads, all image name matches the for attribute from <div class="parent"> ?

Here is the code edited. :)

 let amt = document.getElementsByClassName("child").length; for (let i = 0; i < amt; i++) { var attr = document.getElementsByClassName("child")[i].getAttribute("for") var imgSrc = '../images/content/pagebuilder/' + attr + '.jpg'; document.querySelectorAll(".child")[i].firstElementChild.setAttribute('src', imgSrc); }
 <div class="parent"> <label class="child" for="label_1"> <img src="/site/images/label_1.jpg"> </label> </div> <div class="parent"> <label class="child" for="label_2"> <img src="/site/images/label_2.jpg"> </label> </div> <div class="parent"> <label class="child" for="label_3"> <img src="/site/images/label_3.jpg"> </label> </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