Given any html document with any number of <img>
tags, and using javascript, how can I change all the src attributes of the <img>
tags?
For example change all src attributes in <img>
tags from "http://example.com/somerandomimage.jpg" to "http://example.com/somerandomimage.jpg?foo=bar"
EDIT jquery and other javascript libraries are ok. No need to be vanilla javascript.
Here's how you can change the src for all the images at once with jQuery:
You can use
document.querySelectorAll()
with selector"img[src]"
or"[src]"
;String.prototype.indexOf()
;String.prototype.slice()
.If you are trying to select only
<img>
elements which have asrc
attribute set, you can substitute selector"img[src]"
for"[src]"
; where"[src]"
selects all elements indocument
wheresrc
attribute is present at elementhtml
.This is a one-liner in jQuery:
Wrap it in a document ready handler or include in a script at the end of the body.
Note that the OP confirmed in a comment that the requirement is just to append a specific query string to all img element
src
attributes, and that there is no need to test whether the existingsrc
URL already includes a query string. But if it was possible that a URL might already have a query string then a minor change to the above can handle it by testing for a "?":Using jquery:
In case you intend to replace certain urls only, constrain the selector:
The same operation when having a html string in the first place:
The
<html snippet>
should be well-formed and rooted in a single element.Force a single root as follows:
Note the traversal to the generated root as
wrapAll
returns the original jquery object.