DOM - Class attribute
Table of Contents
1 - About
HTML - The class attribute manipulation in the DOM.
2 - Articles Related
3 - Management
3.1 - Get elements
3.1.1 - Get elements with the Web API
- With the DOM Web API function getElementsByClassName()
3.1.2 - Get elements With Jquery
- With Jquery and a selector
$('.myclass')
3.2 - Is Present
3.3 - Toggle
JQuery Toggle ie: if present, delete, if not present, add..
See also: UI - Toggle or Collapse (Display or hide elements) (On/Off)
3.4 - Add
3.4.1 - Add with Web API
- after selection
document.getElementById(Id).classList.add('is-shown')
document.querySelector('.js-nav').classList.add('is-shown')
- to an target of an event
event.target.classList.add('is-selected')
3.4.2 - Add with Jquery
With the addClass Jquery Method
- The CSS that will apply the color blueviolet to all element with a beauty-blue class
.beauty-blue { color: blueviolet; }
- the Javascript that adds the class beauty blue with the addClass Jquery Method
$( "p" ).addClass( "beauty-blue" )
- the HTML where the p element will get the class beauty-blue at runtime via javascript.
<p>The text should be blue violet because the class 'beauty-blue' was added at runtime</p>
- The result:
You can control it by looking the DOM element with the devtool.
Example: with chrome:
3.5 - Remove
3.5.1 - Remove with Web API
document.getElementById(Id).classList.remove('is-shown')
3.5.2 - Remove with Jquery
With the removeClass Jquery Method
- the Javascript that remove the class beauty blue with the removeClass Jquery Method
$( "p" ).removeClass( "beauty-blue" )
- the HTML where the p element will get the class beauty-blue at runtime via javascript.
<p class="beauty-blue">The text should be black because the class 'beauty-blue' was removed</p>
- A Css that will never be applied because the class will be remove by Javacript
.beauty-blue { color: blueviolet; }
- The result:
You can control it by looking the DOM element with the devtool.
Example: with chrome: