简体   繁体   中英

add multiple index in eq() function jquery

I would like to add the code below to my content :

jQuery( ".pt-cv-content:eq(11)" ).attr( "id" , "content11" );

but I was wonder that

Could I add multiple index in eq()?

For example :

eq(9,10,11).....

thanks

No, you can't, you need multiple selector like so :

jQuery( ".pt-cv-content:eq(11), .pt-cv-content:eq(12)" ).attr( "id" , "content11" );

Or you can store index into an array and loop over it :

var arr = [11,12]; // index 11 and 12
$.each(arr, function(i,e){   
  // this will defined same id name
  // which are not valid
  // as ID must be unique
  // unless you defined it by dynamic values there
  $('.pt-cv-content').eq(e).attr( "id" , "content11" );
});

Noted : You should use dynamic content as ID must be unique.

DEMO

Note

id of element should be unique. Setting elements at index 9 , 10 , 11 respectively, to "content11" would create duplicate id s in document .

Not certain what expected result is ?


Try substituting setting element class for id to avoid setting duplicate id s in document .

To select multiple elements between indexes within a collection of element , try using :lt() , :gt()

 $("div:lt(12):gt(8)").attr("class", "content11") 
 .content11 { color:blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div>0</div> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <div>6</div> <div>7</div> <div>8</div> <div>9</div> <div>10</div> <div>11</div> <div>12</div> <div>13</div> <div>14</div> <div>15</div> <div>16</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM