0

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

Hope that makes sense!

Thanks

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

4 Comments

You're assuming he's using jQuery. You should preface which framework he would need to handle the syntax.
I'm not assuming jQuery, just recommending it (in the first sentence). I also included a link to the jQuery site.
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.
How about var img = $('<img />').attr('src', imageSrc).css('width', '400px')
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.