7null
7null

Reputation: 17

Looking for better/elegant solution to this Jquery code

To continue along my elegant solution series I am trying to figure out how to do this in a better way.

I am cycling through all the a tags and trying to modify the href.

This code works but seems sloppy and would love to know how to do this more efficiently.

$('a').each(function(){
    x=$(this).attr('href').replace(/mls\_number/i,'interior=yes&mls_number');
    $(this).attr('href', x);
});

Upvotes: 0

Views: 147

Answers (3)

AutoSponge
AutoSponge

Reputation: 1454

A POJ cached query with a count-down while loop will be the fastest way to do this:

var elms = Array.prototype.slice.apply(document.getElementsByTagName("a")), 
i = elms.length,
e, 
href;
while (i--) {
    e = elms[i];
    href = e.href.replace(/mls\_number/i,'interior=yes&mls_number');
    e.setAttribute("href", href);
}

Upvotes: 1

MooGoo
MooGoo

Reputation: 48270

$('a').each(function(i, e) { 
  e.href = e.href.replace(/mls\_number/i,'interior=yes&mls_number'); 
});

Or with just Mozilla JS extensions

Array.forEach(document.getElementsByTagName('a'), function(e) {
  e.href = e.href.replace(/mls\_number/i,'interior=yes&mls_number');
});

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

You could use the .attr() function overload which allows you to modify an existing attribute value:

$('a').attr('href', function(index, attr) {
    return attr.replace(/mls\_number/i, 'interior=yes&mls_number');
});

Upvotes: 9

Related Questions