Rich-text Reply

Replace a dinamic href in multiple elements

miguelm 12-18-15
Accepted Solution

Replace a dinamic href in multiple elements

Hi all,

 

I want to replace a link href in multiple elements. This href is different for each element.

 

In the following url: http://www.nh-hoteles.es/hoteles/madrid there is a list of hotels. The hotel name has a href which links to the hotel details page.

 

I want to replace the .hotelName href by the href of the #linkFH button.

 

<a class="hotelName" title="NH Collection Madrid Eurobuilding" itemprop="name" target="_blank" <!-- **THIS HREF --> href="http://www.nh-hoteles.es/hotel/nh-collection-madrid-eurobuilding">NH Collection Madrid Eurobuilding</a>

 

 

 <a id="linkFH" class="fancybox fancybox.iframe btn btn-primary pull-right" <!-- **REPLACE BY THIS -->href="/resources/roomBooking.html?hotel=94&virtualHotel=false" title="">

 

 

 

I tried the following code, but all the .hotelName elements are getting the same href.

$(".hotelItem").each(function(){
var button_link = $("a.fancybox.btn").attr('href');
$('.hotelName').addClass('fancybox fancybox.iframe');
$('.hotelName').attr('href',button_link);
});

 

Thank you, best regards

Level 2

JDahlinANF 12-18-15
 

Re: Replace a dinamic href in multiple elements

[ Edited ]

@miguelm -

 

When you use .each(), you can use $(this) to locate elements relative to the items location in the HTML (in this case, within the wrapper that you are looping through).

$(".hotelItem").each(function(){
	var button_link = $(this).find('a.fancybox.btn').attr('href');
	$(this).find('.hotelName').addClass('fancybox fancybox.iframe').attr('href',button_link);
});

Read this like:

For each hoteItem:

1- find that hotelItem's fancybox's link

2- modify that hotelItem's hotelName

miguelm 12-19-15
 

Re: Replace a dinamic href in multiple elements

Thank you @nap0leon it works fine!
Level 2