user2077308
user2077308

Reputation: 451

How to find and edit a elements' href values without losing query params?

How do I find any element <a> in the page contain the href attr /dailyTickets/front/user.form.php, then change it to /dailyTickets/front/contacts.form.php?

Notice that I want to keep the URL query parameters (id) following the path (user.form.php). For example, changing this:

<a id="User_648_648" href="/dailyTickets/front/user.form.php?id=648">ConseillerUser</a>

to this:

<a id="User_648_648"href="/dailyTickets/front/contacts.form.php?id=648">ConseillerUser</a>

I'm starting with this, but I don't know how to end it:

$('a[href*="dailyTickets/front/user.form.php"]').each(function () { 
    if ($(this).children().length == 0) { 
        ...........
    } 
});

Upvotes: 2

Views: 138

Answers (3)

Bergi
Bergi

Reputation: 664599

You can use the pathname property of the Anchor for not changing host, query or hash.

$('a[href*="dailyTickets/front/user.form.php"]').each(function() {
    this.pathname = "dailyTickets/front/contacts.form.php"; // don't assign to href
});
// or just
$('a[href*="dailyTickets/front/user.form.php"]').prop("pathname", "dailyTickets/front/contacts.form.php");

Upvotes: 1

dfsq
dfsq

Reputation: 193271

This will do the trick and keep all GET parametes:

$('a[href*="dailyTickets/front/user.form.php"]').attr('href', function() { 
    var search  = '/dailyTickets/front/user.form.php',     // 'user.form.php'
        replace = '/dailyTickets/front/contacts.form.php'; // 'contacts.form.php'
    return this.href.replace(search, replace);
});

Upvotes: 1

adeneo
adeneo

Reputation: 318222

There's no need for a loop, jQuery does that interally for you, and just using the selector outright will change any and all elements that match:

$('a[href*="dailyTickets/front/user.form.php"]').attr('href', function(i,href) {
    return href.replace('user.form.php', 'contacts.form.php');
});

Upvotes: 1

Related Questions