user2985842
user2985842

Reputation: 457

Hide id dynamically by jquery

I have three 3 divs

<div id= "product_1"></div>
<div id= "product_2"></div>
<div id= "product_3"></div>
<div id= "product_4"></div>
<div id= "product_5"></div>

I am changing the ids dynamically

var hotelCode = "CUNMXHIDD,CUNMXMAYA,CUNMXDSAN"
var splittedHotelCode = hotelCode.toString().split(',');
jQuery.each(splittedHotelCode, function(i, hotelCode) {
 $("#product_"+ i).attr("id","product_"+ hotelCode);
});

After this I want to hide divs which are not been indexed product_4 and product_5

Now DOM is

<div id= "product_CUNMXHIDD"></div>
<div id= "product_CUNMXMAYA"></div>
<div id= "product_CUNMXDSAN"></div>
<div id= "product_4"></div>
<div id= "product_5"></div>

I dont want to hard code. Is it possible I can hide them by Jquery ?

Upvotes: 0

Views: 41

Answers (2)

Ram
Ram

Reputation: 144729

You could use the length of the array and the slice method.

$('div[id^=product]').slice(splittedHotelCode.length).hide();

Upvotes: 1

AmmarCSE
AmmarCSE

Reputation: 30607

  1. Keep track of index to preserve the last index
  2. Use :gt() to select and then hide all elements that have id that start with product_

var hotelCode = CUNMXHIDD,CUNMXMAYA,CUNMXDSAN
var splittedHotelCode = hotelCode.toString().split(',');
var lastIndex = 0;
jQuery.each(splittedHotelCode, function(i, hotelCode) {
 $("#product_"+ i).attr("id","product_"+ hotelCode);
 lastIndex = i;
});

$('[id^="product_"]:gt('+lastIndex+')').hide();

Upvotes: 0

Related Questions