TruMan1
TruMan1

Reputation: 36078

How to change link href by link text

I have a text below where I want to swap out the login link, but only if the text says "Log In". Sometimes is will say "My Account":

<div id="Login_T4304F19B025">
    <a href="/login1">Log in</a>
</div>

How can I use jQuery to change the href to /login2 if the link text is "Log in"?

Upvotes: 1

Views: 255

Answers (5)

Andy E
Andy E

Reputation: 344517

You can use :contains():

$("a:contains('Log In')").prop("href", "/login2");

However, :contains() works like a wildcard match (e.g. it would also match "Please Log In Now"). If you want a more restrictive search, use .filter():

$("a").filter(function () { 
    return $.text(this) == "Log In";
}).prop("href", "/login2");

Upvotes: 3

Jason Gennaro
Jason Gennaro

Reputation: 34855

var a = $('#Login_T4304F19B025 a').text();

if(a == "Log in" || a == "My account"){
    a.attr("//new link");
}

Upvotes: 0

Alistair Laing
Alistair Laing

Reputation: 973

if ($('#Login_T4304F19B025 a').text() == 'Log in'){
  $('#Login_T4304F19B025 a').attr('href','/login2');
}else{
  $('#Login_T4304F19B025 a').attr('href','/login1');
}

Upvotes: 2

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76870

You could do:

  $('a:contains("Log in")').attr('href', '/login2')

Upvotes: 0

stereoscope
stereoscope

Reputation: 501

$("div a").attr("href","some link to somewhere");

hope this works

Upvotes: 1

Related Questions