Fábio Zangirolami Fábio Zangirolami - 2 months ago 5
Javascript Question

select elements in sequence (by group class name)

how do I select elements created dinamicamentes by groups? I want to select

and work on them. Then select
again and work on them ... Goal is to get grouped elements and insert them classes .....

enter image description here

I want to simulate chat balloons

enter image description here

result final! Thank you all!

enter image description here


Here is a basic jQuery script which checks each element and detecting the following:

  • Check current class
  • If previous sibling has a different class then it will get first
  • If next sibling is of the same class, it will be middle
  • If next sibling is of another class, it will be marked as last
  • If previous and next siblings are of other classes, it will be first middle last

// define your container here
var container = $('.container'),
    currentClass = container.children(":first").attr("class");

// run through each child
container.children('li').each(function() {
  // get current class
  currentClass = $(this).attr("class");
  // first
  if ( $(this).prev().attr("class") !== currentClass ) {
  // middle
  if ( $(this).next().attr("class") === currentClass && $(this).prev().attr("class") === currentClass ) {
  // middle
  if ( $(this).next().attr("class") !== currentClass ) {
  // first middle and last
  if ( $(this).next().attr("class") !== currentClass && $(this).prev().attr("class") !== currentClass ) {
  	$(this).attr("data-order","first middle last");
  // debugging only
  $(this).text( $(this).attr("class") + ': ' + $(this).attr('data-order') );
li[data-order~="first"] {font-weight: bold;}
li[data-order~="last"] {border-bottom:1px solid;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="container">
  <li class="class1"></li>
  <li class="class1"></li>
  <li class="class1"></li>
  <li class="class2"></li>
  <li class="class2"></li>
  <li class="class1"></li>

jsFiddle: https://jsfiddle.net/azizn/40trqhn4/

Note: I used data-order attribute instead class as altering the class name will break the checking function (since it all revolves around class name). You can access the elements through the CSS attribute selectors [data-order="first"] for example.