Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save viniciusban/d0f00ee777dfab1dbd06 to your computer and use it in GitHub Desktop.
Save viniciusban/d0f00ee777dfab1dbd06 to your computer and use it in GitHub Desktop.
Useful functions to handle the class attribute of DOMNode.
"""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
@juancarlospaco
Copy link

Awesome! 😺

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment