tags:

views:

999

answers:

4

I'm trying to append query parameters to links within blocks of text within a class, such as

<div class="container">
consectetur <a href="foo.php?q=bar">adipisicing</a>
</div>

where the ?q=bar is appended. Here's my function:

function appendRef(container,reftag) {
 var Link = $(container).attr("href");
 var afterLink = reftag; 

  $(container).attr({
   href: (Link + afterLink)
   });
}


appendRef(".container a", "?q=bar");

However, this converts every link within the div to the values returned by the first one it sees, rather than processing them uniquely. I'm also looking to be able to filter the function based on part of the original url. Something like

if Link.match(/domain/) { //append the param 
}
A: 

Yes, you are setting the Link variable to a static value (the one of the first href).

You'd have to store the query in a variable like this:

var links = $("." + container + " a");

so links would be an array, then you can loop through it and append the text to its href

antonioh
A: 

I'm not a jQuery guy myself, but I know that css selector will return an array of results. The solution is just to loop through the elements and apply the changes you want. Also, if you want to limit the urls that are affected, I threw an optional match attribute into the function to test the href against.

function appendRef(container,reftag, match) {
        match = match || /.*/
        $(container).each(function() {
           if ($(this).attr('href').match(match)) {
              //do url magic here
           }
        })
}
tj111
+2  A: 

As has been pointed out already when you set you Link variable at the beginning of your function it takes the value of the first element in the set returned by your selector. You need to compute your href for each element in the set before updating it.

You can do this either by calling .each and using .attr inside a closure, or you can make use of the version of attr that accepts a callback and allows you to perform logic on an element by element basis...

$(".container a").attr("href",
    function(idx) { //idx is the index of the element in the set
        return this.href.match(/domain/) ? this.href + afterLink : this.href;
    }
 );
sighohwell
Holy crap, I can't believe I didn't know attr could take a callback like that. Nice.
Paolo Bergantino
A: 

Awesome, all. I built on this, and also modified it so if the original link already has a param, it strips it out and replaces with our new one.

function appendRef(container, reftag, match) {
$(container).each(function() {

    if ($(this).attr('href').match(match)) {         
        var href = $(this).attr('href');              
     var href = href.replace(/\?.*$/,'');
     var href = (href + reftag);  
     $(this).attr('href', href);        

    }
});
}

appendRef(".container a", "?q=foo", "domain");
al