Search code examples
javascriptgetelementbyidurl-parametersgetelementsbyclassname

Add parameters to url using JavaScript


I would like to add url parameter to my img src, can do it using getElementById but can't using getElementsByClassName. I'd prefer using getElementsByClassName as it would make more sense for my purpose. Here is the code I am using:

<img id="parameter" src="http://url-to-image.com/image.jpg" style="width: 100%">

<script>
var image = document.getElementById("parameter");
var imageSrc = image.getAttribute("src");
image.setAttribute("src", imageSrc + "?w=" + viewportWidth + "&h=" + viewportHeight + "&dpr=" + dpr + "&fit=crop");
</script>

The code above works great, but using

<img class="parameter" src="http://url-to-image.com/image.jpg" style="width: 100%">

<script>
var image = document.getElementsByClassName("parameter");
var imageSrc = image.getAttribute("src");
image.setAttribute("src", imageSrc + "?w=" + viewportWidth + "&h=" + viewportHeight + "&dpr=" + dpr + "&fit=crop");
</script>

doesn't add anything to the img src. The url parameter shall be added to all images with the class "parameter". Would be glad if someone could help me on this.


Solution

  • getElementsByClassName returns an array and so you need to either loop over all elements or if you are sure to only having one element, you can select the first element with [0] after image.

    If you want to apply it to all images, you can loop over them. In the following example I'm using querySelectorAll to select the class .parameter.

    const viewportWidth = '100px';
    const viewportHeight = '100px';
    const dpr = 2;
    
    const images = document.querySelectorAll(".parameter");
    images.forEach( ( image ) => {
      const imageSrc = image.getAttribute("src");
      image.setAttribute("src", imageSrc + "?w=" + viewportWidth + "&h=" + viewportHeight + "&dpr=" + dpr + "&fit=crop");
    } );
    <img class="parameter" src="http://url-to-image.com/image.jpg" style="width: 100%">