views:

39

answers:

2

Hi all,

I'm pretty new to javascript and am wondering how on a page with links to images, ie. http://www.example.com/image.jpg I can get them to be changed automatically by javascript to be embedded, ie with tag

Hope that makes sense!

Thanks

+4  A: 

We're particularly fond of the jQuery framework here, as it makes this sort of task very easy. With jQuery on your page, you can easily do this:

$(document).ready(function() {
    $('a[href$=.jpg]').each(function() {
        var imageSrc = $(this).attr('href');
        var img = $('<img />').attr('src', imageSrc);

        $(this).replaceWith(img);
    });
});

This will work specifically for <a> tags whose href attributes end with .jpg You can expand it to other file extensions, of course, but to dynamically determine whether a link leads to an image if the URL is not obvious would be a far greater challenge.

VoteyDisciple
You're assuming he's using jQuery. You should preface which framework he would need to handle the syntax.
nopuck4you
I'm not assuming jQuery, just recommending it (in the first sentence). I also included a link to the jQuery site.
VoteyDisciple
Awesome, thank you. Quickly, how would I then add an image width attribute to the tag as well? Then I should understand the syntax! Thank you.
James Sampson
How about `var img = $('<img />').attr('src', imageSrc).css('width', '400px')`
VoteyDisciple
You rock mate, cheers!
James Sampson
A: 

Do you mean convert all image url's to hyperlinks "pointing" to the images?

var x = document.getElementById('body');
x.innerHTML = x.innerHTML.replace(/(http:\/\/[^ ]+)/g,'<a
href="$1">$1</a>/');

I haven't tested this, but it should work. No third-party frameworks are needed.

From here

alexy13