I have a list of products. Each product has a title and a review link. Currently the titles link directly to the individual product page, and the review links go elsewhere.
I'd like to use a jquery each loop to cycle through each li, take the href from the title (the first link), and apply it to the review link (the second link), so they both point to the product page.
Simplified code would be as follows:
<ul>
<li><a href="product1.html">Product 1</a><a href="review1.html">Review 1</a></li>
<li><a href="product2.html">Product 2</a><a href="review2.html">Review 2</a></li>
<li><a href="product3.html">Product 3</a><a href="review3.html">Review 3</a></li>
</ul>
I thought it would be something like the following:
$("li").each(function(){
var link = $("a:eq(0)").attr('href');
$("a:eq(1)").attr("href", link);
});
But it always uses the same variable "link".
Can someone help me out?
jQuery Misc each() Method The each() method specifies a function to run for each matched element. Tip: return false can be used to stop the loop early.
To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.
Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.
each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.
I am passing this
as an argument to define the context for each iteration of the each()
loop. On each iteration, this
refers to the element in question.
$("li").each(function(){
var link = $("a:eq(0)", this).attr('href');
$("a:eq(1)", this).attr("href", link);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With