Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Appending Attribute Value to Each Element

Tags:

jquery

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.

like image 349
ritsuke Avatar asked Nov 13 '09 18:11

ritsuke


People also ask

How to append value in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

How to add new attribute in jQuery?

Answer: Use the jQuery attr() method You can use the jQuery attr() method to add attributes to an HTML element. In the following example when you click on the "Select Checkbox" button it will add the checked attribute to the checkbox dynamically using jQuery.

How to add attribute in button using jQuery?

You can add attributes using attr like so: $('#someid'). attr('name', 'value'); However, for DOM properties like checked , disabled and readonly , the proper way to do this (as of JQuery 1.6) is to use prop .


1 Answers

Try:

$("img").each(function () {
    var originalSrc = $(this).attr('src');
    $(this).attr('src', 'http://www.domain-name.com/' + originalSrc);    
});
like image 191
spoulson Avatar answered Nov 05 '22 21:11

spoulson