Reputation: 1
I'm looking for a way to find/replace links to images.
For example, the following text:
<a href="http://domain.com/arbitrary-file.jpg">Text</a>
to
<img src="http://domain.com/arbitrary-file.jpg" />
Upvotes: 0
Views: 1576
Reputation: 185
It is possible using Jquery.
stepa:
First take <a>
tag into div
tag.Give unique id to div
tag:
<div id='divtag'><a href="http://domain.com/arbitrary-file.jpg">Text</a> </div>
var value= $('#divtag a').attr('href')
$('#divtag').text('<img src="+ value +">Text</img>')
.
Follow above step to complete your work as you need.
Upvotes: 0
Reputation: 2017
Here's the easiest way to do it in jQuery:
$("a").each(function() {
$(this).replaceWith("<img src='" + $(this).attr("href") + "'>")
})
Image tags don't have inner text. So you would just turn <a href="http://placehold.it/255x255">Something</a>
into <img src="http://placehold.it/255x255">
Edit: if you want to add alt text as what the inner text was you could do:
$("a").each(function() {
$(this).replaceWith("<img src='" + $(this).attr("href") + "' alt='" + $(this).text() +"'>")
})
Here's a snippet you can run:
$("a").each(function() {
$(this).replaceWith("<img src='" + $(this).attr("href") + "' alt='" + $(this).text() +"'>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://placehold.it/255x230">Text</a>
Upvotes: 1
Reputation: 13678
Try this:
var links = document.getElementsByTagName('a');
var i;
var currentLink;
var newImg;
for (i=0; i<links.length; i++) {
currentLink = links[i];
newImg = document.createElement('img');
newImg.src = currentLink.href;
currentLink.parentNode.insertBefore(newImg, currentLink);
currentLink.remove();
}
Upvotes: 0
Reputation: 3294
<a href="http://domain.com/arbitrary-file.jpg" class="test">Text</a>
<script type="text/javascript">
jQuery(document).ready(function(){
var attrib = jQuery('a.test').attr('href');
jQuery('a.test').removeAttr('href');
jQuery('a.test').attr('src',attrib);
});
Upvotes: 0
Reputation: 155698
var linksNodes = document.getElementsByTagName('a');
for( var i = 0; i < linksNodes.length; i++ ) {
var a = linksNodes[i];
if( a.href.endsWith(".jpg") || a.href.endsWith(".png") ) {
var img = document.createElement('img');
img.src = a.href;
a.parentElement.replaceChild( img, a );
}
}
endsWith
is in ES6 but IE11 doesn't support it, Edge does, however. You may need to extend String
:
if( !String.prototype.endsWith ) {
String.prototype.endsWith = function(value) {
var expectedIdx = this.length - value.length;
return this.indexOf( value, expectedIdx ) == expectedIdx;
}
}
Upvotes: 0