简体   繁体   中英

How to target all classes with javascript. No jQuery

I am writing a responsive program that keeps changing the width of sertain elements, corresponding to other elements which have a % based width. Which works fine. But i ran into a problem when i wanted to change all images in side a div to be as big as the grand parent of the images.

JS:

var thebigone = document.getElementById('imgpresentation');
var demimages = document.getElementsByClassName('presentatinthis');

fixtheresponsiveness = setInterval(fixthis,1000);
function fixthis()
{
    demimages.style.width = thebigone.offsetWidth+"px";
}

fixtheresponsiveness();

HTML:

<div id="imgpresentation" class="imgpresentation">
    <div id="slidethemimgpresentation" class="slidethemimgpresentation">
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg1.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg2.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg3.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg4.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg5.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg6.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg7.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg8.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg9.jpg"/>
        <img class="presentatinthis" src="img/billeder/xyachtvisit/xyachtbesoeg10.jpg"/>
    </div>
</div>

It works if i replace "class" with "id" and "getelementsbyclassname" with "getelementbyid" but then it only works on the first img inside the div.

I do not wish to use jQuery, so please do not suggest $('.presentatinthis')

document.getElementsByClassName returns a NodeList , which means you would have to loop over the result to access and set each Node's style

var i = demimages.length;
while (i--) demimages[i].style.width = thebigone.offsetWidth+"px";

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