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.
As other guys said, getElementsByClassName , return list always. I think you can take a look at the querySelector method instead.
var image = document.querySelector(".parameter");
then you don't need to look at the first item in list.
Performance in a performance perspective, getElementByClass would be faster. Performance test
If there is only one element with class name parameter
, use it with index 0,
var image = document.getElementsByClassName("parameter")[0];
The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class names
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%">
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.