Tim
Tim

Reputation: 395

Add base url to all images in an element

I am using a JavaScript editor called NicEdit which doesn't come with an option to change or reference the base URL. I was wondering if this can be done in jQuery or JavaScript?

The image src of all images in the DIV element are the same, <IMG border=0 src="/image.jpg"> except the actually images is stored under a different domain and directory altogether.

I like the src to remain /image.jpg, but make reference to all images into fully-qualified URLs like http://www.domain.com/image.jpg within the that DIV only.

Is this possible?

Upvotes: 0

Views: 2134

Answers (3)

user229044
user229044

Reputation: 239291

Not too difficult with jQuery, but the kind of thing you should consider doing server-side so that your links don't all break when JS is turned off.

$("#div img").each(function (i, e) {
  $(e).attr("src", "http://www.domain.com/" + $(e).attr("src"));
});

Upvotes: 1

Dan Beam
Dan Beam

Reputation: 3927

this allows external images to exist and not be affected (not a very deep check though)

$( 'img' ).not( '[src*="://"]' ).each( function( )
{
    $( this ).attr( 'src', 'http://whatevs.com' + $( this ).attr( 'src' ) ); }
} );

Upvotes: 1

Per H
Per H

Reputation: 1542

I guess this would work:

   $('#divid img').each(function() {
       var newsrc = 'http://www.domain.com' + $(this).attr('src');
       $(this).attr('src', newsrc)
    })

Upvotes: 0

Related Questions