Scroll through all items except the last one

How can I change each element but leave the last one as it is?

jQuery(".diaryevent .field-name-field-category .field-items .field-item a")
.each(function(e) 
{
  var text = jQuery(this).text();
  jQuery(this).html(text + ',');
});

      

Where do I need to add eg. not(":last-child")

or:not(:last-child)

+3


source to share


2 answers


There is no need to cycle each one. With the right selector, you can select all items except the last one.



jQuery(".field-name-field-category > .field-items > .field-item:not(:last) > a")
.text(function(_, text) {
  return text + ',';
});
      

/* Just to see the commas better :) */
a { text-decoration:none;color:#333; }
      

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="field field-name-field-category field-type-taxonomy-term-reference field-label-hidden">
  <div class="field-items">
    <div class="field-item even"><a href="/category/business" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="">Business</a>
    </div>
    <div class="field-item odd"><a href="/category/code" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="">Code</a>
    </div>
    <div class="field-item even"><a href="/category/training" typeof="skos:Concept" property="rdfs:label skos:prefLabel" datatype="">Training</a>
    </div>
  </div>
</div>
      

Run code


+6


source


according to the api, jQuery every parameter of the first function is an array index.

you can compare it with the length of the array to achieve what you want



var arr = jQuery(".diaryevent .field-name-field-category .field-items .field-item a");

arr.each(function(e) 
{
  if(e === arr.length-1) {
      return;
  }
  var text = jQuery(this).text();
  jQuery(this).html(text + ',');
});

      

script: jsfiddle.net/Lgwtcdzs/1

0


source







All Articles