DOM - Class attribute

> (World Wide) Web - (W3|WWW) > The Document Object Model W3C API Interface (DOM)

1 - About

HTML - The class attribute manipulation in the DOM.

Advertising

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

$('.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')
event.target.classList.add('is-selected')
Advertising

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

$( "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

Advertising
web/dom/class.txt · Last modified: 2019/03/12 09:34 by gerardnico