【JavaScript】DOMを操作する時によく使う関数の一覧( プロトタイプ拡張 )
自分がDOMを操作する時によく使用している関数の一覧( プロトタイプ拡張で自作したもの )。
要素を作成
String.prototype.createElement = function() {
return document.createElement( this );
};使用例
const DIV = 'div'.createElement();要素を作成して、クラスを追加
String.prototype.createElementAndAddClass = function( className ) {
const ELEMENT = document.createElement( this );
ELEMENT.classList.add( className );
return ELEMENT;
};使用例
const DIV = 'div'.createElementAndAddClass( 'class-name' );要素を作成して、複数のクラスを追加
String.prototype.createElementAndAddClasses = function( classNames ) {
const ELEMENT = document.createElement( this );
const CLASS_LIST = ELEMENT.classList;
classNames.forEach( function( name ) { CLASS_LIST.add( name ); } );
return ELEMENT;
};使用例
const DIV = 'div'.createElementAndAddClasses( [ 'class-name-1', 'class-name-2' ] );クラスを追加
Element.prototype.addClass = function( name ) {
this.classList.add( name );
};使用例
const ELEMENT = document.getElementById( 'element' );
ELEMENT.addClass( 'class-name' );クラスを除く
Element.prototype.removeClass = function( name ) {
this.classList.remove( name );
};使用例
const ELEMENT = document.getElementById( 'element' );
ELEMENT.removeClass( 'class-name' );クラスの切り替え
Element.prototype.switchClass = function( beforeName, afterName ) {
this.removeClass( beforeName );
this.addClass( afterName );
};使用例
const ELEMENT = document.getElementById( 'element' );
ELEMENT.switchClass( 'class-name-1', 'class-name-2' );クラスを逆の状態に切り替え
Element.prototype.toggleClass = function( name ) {
this.classList.toggle( name );
};使用例
const ELEMENT = document.getElementById( 'element' );
ELEMENT.toggleClass( 'class-name' );スタイルシートの値を取得
Element.prototype.getStylesheetValue = function( propertyName ) {
const STYLE = window.getComputedStyle( this );
const VALUE = STYLE .getPropertyValue( propertyName );
return VALUE;
};使用例
const ELEMENT = document.getElementById( 'element' );
const WIDTH = ELEMENT.getStylesheetValue( 'width' );