dom.Classes.kt Maven / Gradle / Ivy
/*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.dom
import org.w3c.dom.*
/** Returns true if the element has the given CSS class style in its 'class' attribute */
fun Element.hasClass(cssClass: String): Boolean = className.matches("""(^|.*\s+)$cssClass($|\s+.*)""".toRegex())
/**
* Adds CSS class to element. Has no effect if all specified classes are already in class attribute of the element
*
* @return true if at least one class has been added
*/
fun Element.addClass(vararg cssClasses: String): Boolean {
val missingClasses = cssClasses.filterNot { hasClass(it) }
if (missingClasses.isNotEmpty()) {
val presentClasses = className.trim()
className = buildString {
append(presentClasses)
if (!presentClasses.isEmpty()) {
append(" ")
}
missingClasses.joinTo(this, " ")
}
return true
}
return false
}
/**
* Removes all [cssClasses] from element. Has no effect if all specified classes are missing in class attribute of the element
*
* @return true if at least one class has been removed
*/
fun Element.removeClass(vararg cssClasses: String): Boolean {
if (cssClasses.any { hasClass(it) }) {
val toBeRemoved = cssClasses.toSet()
className = className.trim().split("\\s+".toRegex()).filter { it !in toBeRemoved }.joinToString(" ")
return true
}
return false
}