summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/lib.rs35
1 files changed, 33 insertions, 2 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 51baa99..ab5cb84 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -530,10 +530,12 @@ impl Element {
/// classes.
pub fn add_class(&mut self, class: &str) {
if let Some(old) = self.attribute_value("class") {
- self.set_attribute("class", &format!("{old} {class}"));
+ if !old.split_ascii_whitespace().any(|s| s == class) {
+ self.set_attribute("class", &format!("{old} {class}"));
+ }
} else {
self.set_attribute("class", class);
- };
+ }
}
/// Append text to element. It will be escaped, if needed, when
@@ -754,6 +756,35 @@ mod test {
}
#[test]
+ fn can_add_class_to_element() {
+ let mut e = Element::new(Tag::P);
+ e.add_class("foo");
+ let classes: Vec<&str> = e.classes().collect();
+ assert_eq!(classes, ["foo"]);
+ assert_eq!(e.to_string(), r#"<P class="foo"/>"#);
+ }
+
+ #[test]
+ fn can_two_classes_to_element() {
+ let mut e = Element::new(Tag::P);
+ e.add_class("foo");
+ e.add_class("bar");
+ let classes: Vec<&str> = e.classes().collect();
+ assert_eq!(classes, ["foo", "bar"]);
+ assert_eq!(e.to_string(), r#"<P class="foo bar"/>"#);
+ }
+
+ #[test]
+ fn can_add_same_class_twice_to_element() {
+ let mut e = Element::new(Tag::P);
+ e.add_class("foo");
+ e.add_class("foo");
+ let classes: Vec<&str> = e.classes().collect();
+ assert_eq!(classes, ["foo"]);
+ assert_eq!(e.to_string(), r#"<P class="foo"/>"#);
+ }
+
+ #[test]
fn can_add_boolean_attribute_to_element() {
let mut e = Element::new(Tag::P);
e.set_boolean_attribute("foo");