Dres
Dres

Reputation: 1499

How to grab a link from an anchor tag using jQuery

I'm trying to make a click event where when user clicks on an image, they go to the product detail page. I have this:

var $randomCartItemName = $($randomCartItem).find(".cart__item__name").html();

which, when console.log, gives me:

<a href="/us/en_us/shop/a2300?skuId=061006-04&amp;addonSkuId=sku-10-year-standard-warranty"> A2300 </a>

When I click on the div that I want to take me to that page, it takes me to https://www.website.com/us/en_us/<a%20href="/us/en_us/shop/a2500?skuId=061007-04&">A2500</a>

I read some docs, tried a few different things, and didn't get too far. Any recommendations?

Thanks!

Upvotes: 0

Views: 464

Answers (1)

Terry
Terry

Reputation: 66093

You can simply look for the <a> element in $randomCartItemName, retrieve the value of its href attribute and then redirect the browser to the URL using window.location:

var $randomCartItemName = $($randomCartItem).find(".cart__item__name");
var $link = $randomCartItemname.find('a');
var url = $link.attr('href');

window.location = url;

Of course, you can also chain everything at one go:

var $randomCartItemName = $($randomCartItem).find(".cart__item__name");
window.location = $randomCartItemName.find('a').attr('href');

Upvotes: 2

Related Questions