jetlej
jetlej

Reputation: 3392

Replace links to images with img elements w/ jQuery

Using jQuery, I'm trying to replace all links to images (.jpg, .png, .tiff, .gif) within a certain div with img elements to show the image instead of linking to it.

Eg. it would change

<a href="http://domain.com/image.jpg">Any Text Here</a>

to

<img src="http://domain.com/image.jpg"/>

Thank you so much in advance :)

Upvotes: 3

Views: 1228

Answers (2)

David Fullerton
David Fullerton

Reputation: 3254

A simpler version of Neal's answer, using Attribute Ends With selectors:

$("a[href$='.png'], a[href$='.jpg'], a[href$='.tiff'], a[href$='.gif']").each(function() {
    var img = $('<img>',{src: this.href});
    $(this).replaceWith(img);
});

Upvotes: 2

Naftali
Naftali

Reputation: 146310

$('a.img').each(function(){
    //assuming they have the image class
    var img = $('<img>',{src: this.href});
    $(this).replaceWith(img);
});

try that ^_^

UPDATE

if all images dont have the same class:

$('a').each(function(){
    var ext = getfileextension(this.href);
    switch(ext){
        case '.gif':
        case '.png':
        case '.jpg':
            var img = $('<img>',{src: this.href});
            $(this).replaceWith(img);
            break;
    }

});
function getfileextension(filename) 
{ 
    var dot = filename.lastIndexOf("."); 
    if( dot == -1 ) return ""; 
    var extension = filename.substr(dot,filename.length); 
    return extension; 
} 

see this fiddle: http://jsfiddle.net/maniator/3pXEm/

Upvotes: 2

Related Questions