DOM - Class attribute

About

HTML - The class attribute manipulation in the DOM.

Management

Get elements

Get elements with the Web API

  • With the DOM Web API function getElementsByClassName()

Get elements With Jquery

$('.myclass')

Is Present

Toggle

JQuery Toggle ie: if present, delete, if not present, add..

See also: UI - Toggle or Collapse (Display or hide elements) (On/Off)

Add

Add with Web API

  • after selection
document.getElementById(Id).classList.add('is-shown')
document.querySelector('.js-nav').classList.add('is-shown')
event.target.classList.add('is-selected')

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; }
$( "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:

Remove

Remove with Web API

document.getElementById(Id).classList.remove('is-shown')

Remove with Jquery

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:

added


Powered by ComboStrap