Created
January 19, 2015 20:38
-
-
Save viniciusban/d0f00ee777dfab1dbd06 to your computer and use it in GitHub Desktop.
Useful functions to handle the class attribute of DOMNode.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Useful functions to handle the class attribute of DOMNode. | |
Usage: | |
``` | |
>>> el = document['someid'] | |
>>> add_class(el, 'class-one') | |
>>> add_class(el, 'old-class') | |
>>> change_class(el, 'old-class', 'new-class') | |
>>> remove_class(el, 'class-one') | |
>>> print(el.class_name) | |
``` | |
""" | |
def add_class(el, class_): | |
"""Add class_ to el.""" | |
s = el.getAttribute('class') or '' | |
if class_ in s.split(): | |
# already exists. | |
return el | |
s = '{old} {new}'.format( | |
old=s, | |
new=class_ | |
) | |
el.setAttribute('class', s.strip()) | |
return el | |
def remove_class(el, class_): | |
"""Remove class_ from el.""" | |
s = el.getAttribute('class') or '' | |
s = s.replace(class_, '') | |
el.setAttribute('class', s) | |
return el | |
def change_class(el, old, new_): | |
"""Change el's class from `old` to `new_`.""" | |
el = remove_class(el, old) | |
el = add_class(el, new_) | |
return el |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome! 😺