Reputation: 65
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
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', /*...*/);
Upvotes: 1
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
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
Reputation: 7224
$(node).find('li a').each(function() {
$(this).attr('href', 'newlink');
});
Upvotes: 0
Reputation: 7123
Here you go: http://jsfiddle.net/HFj2D/2/
$.each($("#node").find("a"), function(i, link){
$(link).attr("a", newLink[i]);
});
Upvotes: 0
Reputation: 2510
That would be:
for(var i=0; i<3; i++){
$(node, ':nth-child(' + i + ')').children().first().attr('href', newLink[i]);
}
Upvotes: 0