casiokid
casiokid

Reputation: 119

Increment ID in groups of classes

I have some list items grouped by colour in a class and I want to assign a number from 1-6 to each list item ID. So I want to achieve the below using JQuery:

<ul>
  <li class="blue" id="1">Blue</li>
  <li class="blue" id="2">Blue</li>
  <li class="blue" id="3">Blue</li>
  <li class="blue" id="4">Blue</li>
  <li class="blue" id="5">Blue</li>
  <li class="blue" id="6">Blue</li>
  <li class="red" id="1">Red</li>
  <li class="red" id="2">Red</li>
  <li class="red" id="3">Red</li>
  <li class="red" id="4">Red</li>
  <li class="red" id="5">Red</li>
  <li class="red" id="6">Red</li>
<ul>

I have tried the below but it continues the counter from the next colour class instead of resetting to 1:

// get all colours from label data-color attribute
var colors = $("label").map(function() {
  return $(this).data("color");
});


var $ul = $("ul#slideImages"),
$swatches = $(".swatches");

// for each colour, create and add colour class to <li>
$.each(colors, function(i, color) {
  var $li = $("<li/>", {
    class: color
  });
  $ul.append(new Array(7).join($li.get(0).outerHTML));
});

// for each <li> colour class add an incremented ID 
var number = 0;
$('ul#slideImages li').each(function(i){
   number++;
   $(this).attr('id', number);
});

Upvotes: 0

Views: 121

Answers (2)

Tejesh
Tejesh

Reputation: 189

html

<ul id="slideImages">
  <li class="blue" >Blue</li>
  <li class="blue" >Blue</li>
  <li class="blue" >Blue</li>
  <li class="blue" >Blue</li>
  <li class="blue" >Blue</li>
  <li class="blue" >Blue</li>
  <li class="red" >Red</li>
  <li class="red" >Red</li>
  <li class="red" >Red</li>
  <li class="red" >Red</li>
  <li class="red" >Red</li>
  <li class="red" id="6">Red</li>
<ul>

js

// get all colours from label data-color attribute
colors = ['blue','red'];

var colorCount = {};
for(var i=0;i<colors.length;i++){
    colorCount[colors[i]] = 0;
}
//colorCount = {c1:0,c2:0,c3:0}



// for each <li> colour class add an incremented ID 
$('ul#slideImages li').each(function(i){
   var color = $(this).attr('class');//or whatever attr which gives color
   colorCount[color] += 1;
   $(this).attr('id', colorCount[color]);
});

Having multiple elements with same ID values is generally not advised. But you can process them if you can do it carefully with combined selectors which will make it unique (I would advise not to)

PS: I have skipped some part of js, which is not relevant for this question

jsFiddle: http://jsfiddle.net/ntjuxLy4/1/

Upvotes: 1

Rahul Desai
Rahul Desai

Reputation: 15491

IDs need to be unique for every element inside HTML. If you do not follow this, you will produce an invalid HTML.

My suggestion is to keep your code as it is since it has unique ID for every element.

As suggested by @dotty, you may use data attributes for adding metadata to your elements.

Upvotes: 0

Related Questions