I'd like to dynamically add Tag in all Images in a specific div with a rel-Attribute.
eg my Code in HTML
<div id="content">
<img src="images/1.jpg" alt="Pic One" />
<img src="images/2.jpg" alt="Pic Two" />
(...)
</div>
After the JavaScript function, it should be like this:
<div id="content">
<a href="images/1.jpg" rel="prettyPhoto"><img src="images/1.jpg" alt="Pic One"/></a>
<a href="images/2.jpg" rel="prettyPhoto"><img src="images/2.jpg" alt="Pic One"/></a>
(...)
</div>
Is there a suitable way to do this? Perhaps with regex?
Try this:
$('#content img').each(function(){
$(this).wrap('<a href="'+$(this).attr('src')+'" rel="prettyPhoto"></a>');
});
JavaScript alone can do this. First, select all the images inside the div:
var images=document.getElementById("content").querySelectorAll("img");
Then, you'll want to loop through each and edit it:
for (var I=0; I<images.length; I++){
images[I].outerHTML="<a href='"+images[I].src+"' rel='prettyPhoto'>"+images[I].outerHTML+"</a>";
}
That should do it.
$("#content > img").each(function(){
$(this).wrap("<a>");
});
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.