7

I am trying to append an additional url chunk to an existing attribute and simply update it.

$("img").each(function (i) {
    var originalSrc = $("img").attr('src');
    $("img").attr('src', 'http://www.domain-name.com/' + originalSrc);    
});

$("a").each(function (i) {
    var originalHref = $("a").attr('href');
    $("a").attr('href', 'http://www.domain-name.com/' + originalHref);    
});

It is counting all elements and appending a long string to the final attribute. I understand what's going on, but I'm not sure the correct way to go about this. This is obviously wrong.

Essentially, I'm scrubbing a remote page and I need to reset all relative connections to absolute.

2
  • I'm not certain I understand, what's the wrong part of this? Commented Nov 13, 2009 at 18:59
  • I didn't drink enough coffee this morning, that's what! :-) Thanks guys. Such a silly thing to have a mistake over. Commented Nov 13, 2009 at 19:04

5 Answers 5

28

Try:

$("img").each(function () {
    var originalSrc = $(this).attr('src');
    $(this).attr('src', 'http://www.domain-name.com/' + originalSrc);    
});
Sign up to request clarification or add additional context in comments.

Comments

8

Even less work with (compare http://api.jquery.com/attr/) :

$("img").attr('src', function(i, val){
   return 'http://www.domain.com/' + val;
});

$("a").attr('href', function(i, val){
   return 'http://www.domain.com/' + val;
});

Greets

Comments

1

Since you are using the each method to loop over your elements, you should use the this keyword inside the callback function, to refer to the currently iterated element:

$("img").each(function (i) {
    var image = $(this), // 'this' is the image element being iterated
        originalSrc = image.attr('src');

    image.attr('src', 'http://www.domain-name.com/' + originalSrc);    
});

Comments

0

Using your code structure:

$("img").each(function (i) {
    var $img = $(this);
    var originalSrc = $img.attr('src');   // use "this" in the $() function to get the current element...
    $img.attr('src', 'http://www.domain-name.com/' + originalSrc);    
});

$("a").each(function (i) {
    var $a = $(this);
    var originalHref = $a.attr('href');
    $a.attr('href', 'http://www.domain-name.com/' + originalHref);    
});

Make sure to use $(this) inside of jQuery's callback functions to retrieve the 'current' node in the node list.

Comments

0

Inside each function use $(this) instead of $(a) and $(img).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.