Evan
Evan

Reputation: 3511

Change link attributes within a class using jquery

Without manually assigning an ID to each href, the goal would be to change the URLs for both hrefs to a different URL

<div class="example">
        <p><a href="http://www.google.com/example?test1332">Test Site</a></p>
        <p><a href="http://www.google.com/example?test1332">Test Site</a></p>
</div>

This is my jquery attempt which is not working

$(".example").each(function() {
    this.setAttribute("href", this.getAttribute("href").replace("http://www.test.com"));
});

This is my fiddle http://jsfiddle.net/n322j/

Upvotes: 0

Views: 42

Answers (2)

gagan
gagan

Reputation: 1

another way of doing this.

<script>
$("document").ready(function (){
$("div p a").attr('href',"http://www.google.com");
});
</script>

it also works fine.

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382170

You seem to want

$('.example a').attr('href', "http://www.test.com");

If you'd want to only replace part of the URL, that is keep everything apart http://www.google.com, then you could do

$(".example a").attr('href', function(i, href) {
   return href.replace("http://www.google.com", "http://www.test.com");
});

Demonstration

Upvotes: 4

Related Questions