Sometimes I need to manipulate the class attribute of html elements,
adding or removing classes. As I couldn't find any helpers to perform
this task I wrote them myself. Maybe someone finds them useful.
Cheers,
Chris
import scala.xml._
/** Add a value to the class attribute, removing any duplicates.
*/
def addClass(e: Elem, cls: String): Elem = {
val m = e.attributes
e % (
m("class") match {
case null =>
m append (new UnprefixedAttribute("class",
cls, Null))
case classes =>
m append (new UnprefixedAttribute("class",
(Set(classes.text.split("\\s+"): _*) +
cls) mkString " ",
Null))
})
}
/**
* Remove a value from the class attribute. If no values remains,
the whole class attribute is removed.
*/
def removeClass(e: Elem, cls: String): Elem = {
val m = e.attributes
m("class") match {
case null => e
case classes =>
Set(classes.text.split("\\s+"): _*) - cls match {
case s if s.size == 0 =>
Elem(e.prefix, e.label, m.remove("class"),
e.scope, e.child: _*)
case s =>
e % m.append(new UnprefixedAttribute("class",
s mkString " ", Null))
}
}
}
--
You received this message because you are subscribed to the Google Groups
"Lift" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/liftweb?hl=en.