I have this HTML code created by a javascript file, which is not understandable because it was created using GWT(Google Web Toolkit).
<img style="z-index: 6; width: 116px; position: absolute; left: 84px; top: 174px;" src="spiral/sample9.jpg">
<img style="z-index: 12; width: 197px; position: absolute; left: 0px; top: 161px;" src="spiral/sample1.jpg">
<img style="z-index: 1; position: absolute; left: 659px; top: 213px; width: 85px; opacity: 0.04; display: none;" src="spiral/sample17.jpg">
<img style="z-index: 1; position: absolute; left: 644px; top: 208px; width: 85px; opacity: 0.08; display: none;" src="spiral/sample18.jpg">
Now I need to add the tag <a>
before every image, using as src
, part of the src
of the image. For example: " href="../tmp.php?title=sample9.mp4
"
Any clue how can I do this?
The output I want to create is something like this:
<a href="../tmp.php?title=sample9.mp4"><img style="z-index: 6; width: 116px; position: absolute; left: 84px; top: 174px;" src="spiral/sample9.jpg"></a>
With jQuery, you can use wrap()
to do this:
$('img').each(function() {
$(this).wrap($('<a/>', {href: this.src}));
});
What you want is to wrap and to build the right href you can use a regular expression :
$('img').wrap(function(){
return $('<a>').attr(
'href',
'../tmp.php?title=' + this.src.match(/\/(.*?)\.jpg$/)[1] + '.mp4'
)
});
Quite apart from your obvious lack of understanding of the querySelector
function, you also expect </img>
to work (it doesn't, it's a void element)...
Here's how you should go about it, with comments to explain:
var imgs, l, i, img, par, a; // prepare some variables
imgs = document.getElementByTagName('img');
// get all images on the page
l = imgs.length; // save the number of images (for performance reasons)
for( i=0; i<l; i++) { // loop through all images
img = imgs[i]; // for easire access
par = img.parentNode; // get the parent of the current image
a = document.createElement('a');
// create a new link
a.href = "../tmp.php?title="+img.src.match(/([^\/.]+\.\w+$/)[1]+".mp4";
// extract the right part from the image source
// and put it into the link's href
par.insertBefore(a,img); // insert the link before the image
a.appendChild(img); // move the image so that it is inside the link
}
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.