Modifying Classes and Attributes
Modifying classes of elements is as easy as:
myElement.classList.add('foo')
myElement.classList.remove('bar')
myElement.classList.toggle('baz')
You can read a more in-depth disussion of how to modify classes in thisquick tip by Yaphi Berhanu. Element properties can be accessed like any other object’s properties
// Get an attribute value
const value = myElement.value
// Set an attribute as an element property
myElement.value ='foo'
// Set multiple properties using Object.assign()
Object.assign(myElement, {
value: 'foo',
id: 'bar'
})
// Remove an attribute
myElement.value = null
Note that there are also the methods.getAttibute()
,.setAttribute()
and .removeAttribute()
. These directly modify the HTML attributes (as opposed to the DOM properties) of an element, thus causing a browser redraw (you can observe the changes by inspecting the element with your browser’s dev tools). Not only is such a browser redraw more expensive than just setting DOM properties, but these methods also can have unexpected results.
As a rule of thumb, only use them for attributes that don’t have a corresponding DOM property (such ascolspan
), or if you really want to “persist” those changes to the HTML.