Domanda

I want to insert new elements, but it has to be between specific elements. The only way to distinguish these elements is by their content.

I want to insert header elements that will split up this list alphabetically. How can I do this?

<p>Aardvark</p>
<p>Alligator</p>
<p>Bear</p>
<p>Beaver</p>
<p>Cat</p>
<p>Cow</p>
...
È stato utile?

Soluzione

Alright, let's get some serious code right done right now.

I'm going to try to make this dynamic!

$letter = ''
$("//p[not(contains(@class,'starts-with'))][1]") {
  # get the first p that doesn't have the class
  $add_header = "false"
  text() {
    capture(/\A(\w)/) {
      # get the first letter and set it to a variable 
      match($letter) {
        with($1) {
          #do nothing
        }
        else() {
          $letter = $1
          $add_header = "true"
        }
      }
    }
  }
  match($add_header) {
    with(/true/) {
      insert_before("h1", "Starts With: "+$letter)
      $("self::*|following-sibling::p[contains(text(), '"+$letter+"')]") {
        add_class("starts-with-" + $letter)
      }
    }
  }
}

Altri suggerimenti

Give this a shot. It will work on any list, even if the elements aren't grouped by first letter.

$add_header = "true"
text() {
  replace(/^(.)/) {
    $first_letter = $1
  }
}

# If the header section already exists, move this element inside
move_to("preceding-sibling::div[@class='starts-with-"+$first_letter+"']") {
  $add_header = "false" 
}

# If the header section doesn't exist, wrap the element 
match($add_header, /true/) {
  wrap("div") {
    add_class("starts-with-" + $1)
  }
}

It would be pretty trivial to wrap this into a function. After this, the next logical function to write would be alphabetize, as well as using $first_letter to match both lower and upper case versions of the letter found.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top