Nere
Nere

Reputation: 4097

How I can add additional path to img src using jquery in a certain div?

I'm currently have this input for my img tag:

  <div id="myDiv">
      <img src="/assets/images/upload/test1.jpg" />
      <img src="/assets/images/upload/test2.jpg" />
      <img src="/assets/images/upload/test3.jpg" />
  </div>

How I can use jquery to add image path like /newfolder/ to all image tags in myDiv using jquery? I found that jquery can alter the image src...for example

$('#myDiv img').attr('src','/newfolder/assets/images/upload/test.jpg')

Now..how I can continuously find other images in myDiv and add pre-path like /newfolder/ to all image src in myDiv?

Upvotes: 0

Views: 930

Answers (1)

Andre Lehnert
Andre Lehnert

Reputation: 531

var picRoot="/newfolder";

$('#myDiv img').each(function(){
    if ( $(this).attr('src').indexOf(picRoot)!== 0){
        $(this).attr('src', picRoot + $(this).attr('src'));
    }
});

Call it, if your content changes.

Upvotes: 1

Related Questions