nazshal
nazshal

Reputation: 65

replacing a bunch of href with jquery. need just code improvement

I try to change the href of 3 a-tags with jquery. At the moment, I do that with normal javascript.

var catNav = $('ul.nav'),
newLink = ['new1/','new2','nwe3/'];

catNav.attr('id','node');
var node =document.getElementById('node');
for(var i=0; i<3; i++){
node.childNodes[i].firstChild.href=newLink[i];
}

what i want from you. just teach me how i do this

for(var i=0; i<3; i++){
    node.childNodes[i].firstChild.href=newLink[i];
}

with jquery.

here's an example http://jsfiddle.net/HFj2D/1/

Upvotes: 0

Views: 130

Answers (6)

Felix Kling
Felix Kling

Reputation: 816262

Just use attr [docs]:

$('ul.nav > li').slice(0,3).children('a:first-child').attr('href', function(i) {
    return newLink[i];
});

I also tried to select the elements the same way you did with plain JavaScript, i.e. the first three list entries and the first a element.

That said, if your array contains as many new links as you have a elements in your menu, then you can simplify the selection to:

$('ul.nav a').attr('href', /*...*/);

DEMO

Upvotes: 1

Alnitak
Alnitak

Reputation: 339786

This should do the whole thing:

var newLink = ['new1/','new2','nwe3/'];

$("ul.nav").attr('id', 'node').find('a').each(function(index, el) {
    this.href = newLink[index];
});

Ideally you should already have an ID on the <ul> tag anyway, though.

Upvotes: 2

Blazes
Blazes

Reputation: 4779

This will find all of the links beneath the catNav node (you already have the node), and assign the new href for each.

catNav.find('a').each(function(index) { $(this).attr('href', newLink[index]); }) 

Upvotes: 1

Nikolay Dyankov
Nikolay Dyankov

Reputation: 7224

$(node).find('li a').each(function() { $(this).attr('href', 'newlink'); });

Upvotes: 0

RSG
RSG

Reputation: 7123

Here you go: http://jsfiddle.net/HFj2D/2/

$.each($("#node").find("a"), function(i, link){
  $(link).attr("a", newLink[i]);
});

Upvotes: 0

Mihalis Bagos
Mihalis Bagos

Reputation: 2510

That would be:

for(var i=0; i<3; i++){
    $(node, ':nth-child(' + i + ')').children().first().attr('href', newLink[i]);
}

Upvotes: 0

Related Questions