Recent posts

Recent comments

Archive

Calender

«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

Use the Google Translate, if you want to read this page in your language.
But its translation is probably inaccurate.
Go to the Google Translate.





Polyfill

1. IE 8 이상에서 "classList"를 사용할 수 있는 방법.

"Eli Grey"이라는 사람이 작성한 내용이며,
"classList"가 적용되지 않는 브라우저를 위해서, 추가해야될 소스코드이다.
IE 8 버전부터 사용이 가능하다.


"Eli Grey"의 소스코드를 직접 사용해 본 결과,
"add(), remove(), toggle()" 중에서,
"add()"를 예로 들자면, "IE 10"과 "IE 11"에서, "class"가 하나만 추가되었다.


따라서,
"add(), remove(), toggle()" 함수에서 발생하는 오류를 바로잡기 위해서,
원본 내용을 아주 조금만 수정하였다.


 
/* 
 * classList.js: Cross-browser full element.classList implementation. 
 * 1.1.20150312 
 * 
 * By Eli Grey, https://eligrey.com/ 
 * License: Dedicated to the public domain. 
 * See https://github.com/eligrey/classList.js/blob/master/LICENSE.md 
 */ 

/*global self, document, DOMException */ 

/*! @source https://github.com/eligrey/classList.js/blob/master/classList.js */ 

if ( "document" in self ){ 

    // Full polyfill for browsers with no classList support 
    // Including IE < Edge missing SVGElement.classList 
    if (  ! ( "classList" in document.createElement("_") ) 
	|| document.createElementNS && !( "classList" in document.createElementNS("http://www.w3.org/2000/svg","g") )  ){ 

        ( function ( view ){ 

        "use strict"; 

        if ( ! ( "Element" in view ) ) return; 

            var classListProp = "classList", 
                 protoProp = "prototype", 
                 elemCtrProto = view.Element[ protoProp ], 
                 objCtr = Object; 

            var strTrim = String[ protoProp ].trim || function(){  return this.replace( /^\s+|\s+$/g, "" );  }; 
            var arrIndexOf = Array[ protoProp ].indexOf || function( item ){ 
                        for ( var x = 0; x < this.length; x++ ){ 
                                if ( x in this && this[ x ] === item ){  return x;  } 
                        } 
                        return -1; 
            }; 
            // Vendors: please allow content code to instantiate DOMExceptions 
            var DOMEx = function( type, message ){ 
                        this.name = type; 
                        this.code = DOMException[ type ]; 
                        this.message = message; 
            }; 
            var checkTokenAndGetIndex = function( classList, token ){ 
                        if ( token === "" ){ 
                                throw new DOMEx( "SYNTAX_ERR", "An invalid or illegal string was specified" ); 
                        } 
                        if (  /\s/.test( token )  ){ 
                                throw new DOMEx( "INVALID_CHARACTER_ERR", "String contains an invalid character" ); 
                        } 
                        return arrIndexOf.call( classList, token ); 
            }; 
            var ClassList = function( elem ){ 
                        var trimmedClasses = strTrim.call( elem.getAttribute("class") || "" ), 
                             classes = trimmedClasses ? trimmedClasses.split( /\s+/ ) : [], 
                             x = 0, 
                             len = classes.length; 
                        for ( ; x < len; x++ ){  this.push( classes[x] );  } 
                        this._updateClassName = function(){  elem.setAttribute( "class", this.toString() );  }; 
            }; 
            var classListProto = ClassList[ protoProp ] = []; 
            var classListGetter = function(){  return new ClassList( this );  }; 

            // Most DOMException implementations don't allow calling DOMException's toString() 
            // on non-DOMExceptions. Error's toString() is sufficient here. 
            DOMEx[ protoProp ] = Error[ protoProp ]; 

            classListProto.item = function( index ){  return this[ index ] || null;  }; 
            classListProto.contains = function( token ){ 
                        token += ""; 
                        return checkTokenAndGetIndex( this, token ) !== -1; 
            }; 
            classListProto.add = function(){ 
                        var tokens = arguments, x = 0, len = tokens.length, token, updated = false; 
                        do { 
                                token = tokens[ x ] + ""; 
                                if ( checkTokenAndGetIndex( this, token ) === -1 ){ 
                                        this.push( token ); 
                                        updated = true; 
                                } 
                        } 
                        while ( ++x < len ); 

                        if ( updated ){  this._updateClassName();  } 
            }; 
            classListProto.remove = function(){ 
                        var tokens = arguments, x = 0, len = tokens.length, token, updated = false, index; 
                        do { 
                                token = tokens[ x ] + ""; 
                                index = checkTokenAndGetIndex( this, token ); 
                                while ( index !== -1 ){ 
                                        this.splice( index, 1 ); 
                                        updated = true; 
                                        index = checkTokenAndGetIndex( this, token ); 
                                } 
                        } 
                        while ( ++i < len ); 

                        if ( updated ){  this._updateClassName();  } 
            }; 
            classListProto.toggle = function( token, force ){ 
                        token += ""; 

                        var result = this.contains( token ), 
                             method = result ? force !== true && "remove" : force !== false && "add"; 

                        if ( method ){  this[ method ]( token );  } 

                        if ( force === true || force === false ){  return force;  } 
                        else {  return !result;  } 
            }; 
            classListProto.toString = function(){  return this.join( " " );  }; 

            if ( objCtr.defineProperty ){ 
                    var classListPropDesc = { get: classListGetter, enumerable: true, configurable: true }; 

                    try {  objCtr.defineProperty( elemCtrProto, classListProp, classListPropDesc );  } 
                    catch ( ex ) { // IE 8 doesn't support enumerable:true 
                            if ( ex.number === -0x7FF5EC54 ){ 
                                    classListPropDesc.enumerable = false; 
                                    objCtr.defineProperty( elemCtrProto, classListProp, classListPropDesc ); 
                            } 
                    } 
            } 
            else if (  objCtr[ protoProp ].__defineGetter__ ){ 
                        elemCtrProto.__defineGetter__( classListProp, classListGetter ); 
            } 
        }( self ) ); 
    } 
} 

// There is full or partial native classList support, so just check if we need
// to normalize the add/remove and toggle APIs. 
if( "DOMTokenList" in this ){ 
    (function () {
        "use strict";

        var testElement = document.createElement( "_" );

        testElement.classList.add( "c1", "c2" );

        // Polyfill for IE 10/11 and Firefox <26, where classList.add and
        // classList.remove exist but support only one argument at a time. 
        if (  ! testElement.classList.contains( "c2" )  ){
                var createMethod = function( method ){
                        var original = DOMTokenList.prototype[ method ];

                        DOMTokenList.prototype[ method ] = function( token ){
                                for ( var x = 0; x < arguments.length; x++ ){
                                        token = arguments[ x ];
                                        original.call( this, token );
                                }
                        };
                };
                createMethod( "add" );
                createMethod( "remove" );
        }

        testElement.classList.toggle( "c3", false );

        // Polyfill for IE 10 and Firefox <24, where classList.toggle does not
        // support the second argument. 
        if (  testElement.classList.contains( "c3" )  ){
                var _toggle = DOMTokenList.prototype.toggle;

                DOMTokenList.prototype.toggle = function( token, force ){
                        if ( 1 in arguments && ! this.contains( token ) === !force ){
                                return force;
                        } 
                        else {  return _toggle.call( this, token );  }
                };

        }

        testElement = null;
    }());
} 
 


2. IE 7 이하에서, "classList"를 대신할 getClasses() 함수.

언제나 골칫거리인 익스플로러 때문에,
"classList"를 대신할 함수를 작성하였다.


 
/* 
 * source : https://tonks.tistory.com/161#_javascript_classList 
 * last modified : 2016. 11. 2. 
 */ 
function getClasses ( tag ){ 

     // "빈 문자열 또는 띄어쓰기가 포함된 문자열"에 대한 예외 처리. 
     // Exception handling when a string contains spaces or it's empty string. 
     var checkString = function ( string ){ 
          var isEmpty = ( string === "" ) ? true : ( /\s/.test( string ) ? false : null ); 
          if ( isEmpty == null ){  return;  }

          var name = ( isEmpty ) ? "SyntaxError" : "InvalidCharacterError"; 
          var message = ( isEmpty ) ? "An invalid or illegal string was specified." : "String contains an invalid character."; 
          var code = ( isEmpty ) ? 12 : 5; 
          var constants = ( isEmpty ) ? "SYNTAX_ERR" : "INVALID_CHARACTER_ERR";  

          try {  throw new Error( message );  } 

          catch ( error ){
               error.name = name; 
               error.code = code; 
               error[ constants ] = code; 
               throw error; 
          } 
     }; 

     var trimmed = tag.className.replace( /^\s+|\s+$/g, "" ).replace( /\s+/g, " " ); 

     var classes = ( trimmed.length == 0 ) ? [ ] : trimmed.split( " " ); 

     if ( ! Array.prototype.indexOf ){ 
          classes.indexOf = function ( item, index ){ 
               var length = this.length; 
               if ( length === 0 ){  return -1;  } 
               var index = Math.floor( index ) || 0; 
               var abs = Math.abs( index ); 
               if ( index < 0 ){  index = ( abs > length ) ? 0 : length - abs;  } 
               for ( index; index < length; index++ ){  if ( this[ index ] === item ) return index;  } 
               return -1; 
          }; 
     } 

     classes.toString = function (){  return this.join( " " );  }; 

     classes.item = function ( index ){  return this[ index ];  }; 

     classes.contains = function ( toBeSearched ){ 
          if ( this.length < 1 ){  return false;  } 
          var searchString = "" + toBeSearched; 
          if ( searchString === "" || /\s/.test( searchString ) ){  return false;  } 
          return this.indexOf( searchString ) != -1;
     }; 

     classes.add = function (){ 
          var n, newClass, isChanged = false; 
          for ( n = 0; n < arguments.length; n++ ){ 
               newClass = "" + arguments[ n ]; 
               checkString( newClass ); 
               if ( this.indexOf( newClass ) < 0 ){ 
                    this.push( newClass ); 
                    isChanged = true; 
               } 
          } 

          if ( isChanged ){  tag.className = this.toString();  } 
     }; 

     classes.remove = function(){ 
          if ( this.length < 1 ){  return;  } 

          var n = 0, index, toBeRemoved, isChanged = false; 
          for ( ; n < arguments.length ;  ){ 
               toBeRemoved = "" + arguments[ n ]; 
               checkString( toBeRemoved ); 
               index = this.indexOf( toBeRemoved ); 
               if ( index < 0 ){  n++;  } 
               else { 
                    this.splice( index, 1 ); 
                    isChanged = true; 
               }
          } 

          if ( isChanged ){  tag.className = this.toString();  } 
     }; 

     classes.toggle = function( toToggle, boolean ){ 
                var isContained = this.contains( toToggle ); 
                if ( isContained === boolean ){  return boolean;  } 
                ( isContained ) ? this.remove( toToggle ) : this.add( toToggle ); 

                return !( isContained ); 
        }; 


     return classes; 
} 
 


"classList & getClasses()" 사용법.

1. classList

"classList"는 태그의 "class"에 설정되어 있는 내용을, 배열 형태로 가져온다.


<button onclick="testing()"> 클릭하세요 </button> 
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>

<p id="demo1"> </p>
<p id="demo2"> </p>
<p id="demo3"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    if ( "classList" in tag ){ // "classList"를 사용할 수 있다면,  
        var classes = tag.classList; 
        document.getElementById( "demo1" ).innerHTML = classes; 
        document.getElementById( "demo2" ).innerHTML = classes[ 2 ]; 
        document.getElementById( "demo3" ).innerHTML = tag.className; 
    } 
} 
</script>


2. getClasses()

아래는, 내가 작성한 "getClasses()" 함수를 이용하는 방법이다.


<button onclick="testing()"> 클릭하세요 </button> 
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>

<p id="demo1"> </p>
<p id="demo2"> </p>
<p id="demo3"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    var classes = getClasses( tag ); 
    document.getElementById( "demo1" ).innerHTML = classes; 
    document.getElementById( "demo2" ).innerHTML = classes[ 2 ]; 
    document.getElementById( "demo3" ).innerHTML = tag.className; 
} 
</script>


3. 'classList'와 'getClasses()'를 함께 사용하기.

 
<button onclick="testing()"> 클릭하세요 </button>
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>

<p id="demo1"> </p>
<p id="demo2"> </p>

<script type="text/javascript">
function testing() { 
    var tag = document.getElementById( "myDiv" ); 
    var classes = tag.classList || getClasses( tag ); 

    document.getElementById( "demo1" ).innerHTML = classes[ 2 ]; 
    document.getElementById( "demo2" ).innerHTML = tag.className; 
} 
</script>


4. classList.length & getClasses().length

classList의 "length"는, "classList" 안에 총 몇 개의 "class"가 들어있는지를 알려준다.
즉, 배열 형태인, "classList"의 길이값이다.


<button onclick="testing()"> 클릭하세요 </button> 
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>
<p id="demo"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    if ( "classList" in tag ){ 
        var classList = tag.classList; 
        var length = classList.length; 
        document.getElementById( "demo" ).innerHTML = length; 
    } 
} 
</script>


<button onclick="testing()"> 클릭하세요 </button> 
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>
<p id="demo"> </p>

<script type="text/javascript">
function testing() { 
    var tag = document.getElementById( "myDiv" ); 
    var classList = getClasses( tag ); 
    var length = classList.length; 
    document.getElementById( "demo" ).innerHTML = length; 
} 
</script>


<button onclick="testing()"> 클릭하세요 </button> 
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>
<p id="demo"> </p>

<script type="text/javascript">

function testing() { 
    var tag = document.getElementById( "myDiv" ); 
    var classList = tag.classList || getClasses( tag ); 
    var length = classList.length; 
    document.getElementById( "demo" ).innerHTML = length; 
} 
</script>


5. classList.item() & getClasses().item()

classList의 "item()" 함수는,
"classList" 안에 들어있는 항목(item) 중에서 하나를 가져올 때 사용된다.
"item()" 함수의 괄호 안에, 가져올 항목의 위치를 넣어주면 된다.


<button onclick="testing()"> 클릭하세요 </button> 
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>
<p id="demo1"> </p>
<p id="demo2"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    if ( "classList" in tag ){ 
        var classList = tag.classList; 
        var firstClass = classList.item( 0 ); 
        var secondClass = classList.item( 1 ); 
        document.getElementById( "demo1" ).innerHTML = firstClass; 
        document.getElementById( "demo2" ).innerHTML = secondClass; 
    } 
} 
</script>


<button onclick="testing()"> 클릭하세요 </button> 
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>
<p id="demo1"> </p>
<p id="demo2"> </p>

<script type="text/javascript">
function testing() { 
    var tag = document.getElementById( "myDiv" ); 
    var classList = getClasses( tag ); 
    var firstClass = classList.item( 0 ); 
    var secondClass = classList.item( 1 ); 
    document.getElementById( "demo1" ).innerHTML = firstClass; 
    document.getElementById( "demo2" ).innerHTML = secondClass; 
} 
</script>


<button onclick="testing()"> 클릭하세요 </button>
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>
<p id="demo1"> </p>
<p id="demo2"> </p>

<script type="text/javascript">
function testing() { 
    var tag = document.getElementById( "myDiv" ); 
    var classList = tag.classList || getClasses( tag ); 
    var firstClass = classList.item( 0 ); 
    var secondClass = classList.item( 1 ); 
    document.getElementById( "demo1" ).innerHTML = firstClass; 
    document.getElementById( "demo2" ).innerHTML = secondClass; 
} 
</script>


6. classList.contains() & getClasses().contains()

classList의 "contains()"는,
태그의 "class"에 어떤 "class"가 들어있는지를 확인하고 싶을 때 사용한다.

확인하려는 "class"가 이미 들어있다면, 결과는 true이다.
포함되어있지 않다면, "contains()"가 실행된 결과는 false이다.


<button onclick="testing()"> 클릭하세요 </button> 
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>
<p id="demo1"> </p>
<p id="demo2"> </p>

<script type="text/javascript">
function testing() { 
    var tag = document.getElementById( "myDiv" ); 
    if ( "classList" in tag ){ 
        var classList = tag.classList; 
        var check1 = classList.contains( "anotherStyle" ); 
        document.getElementById( "demo1" ).innerHTML = check1; 
        var check2 = classList.contains( "someClass" ); 
        document.getElementById( "demo2" ).innerHTML = check2; 
    } 
} 
</script>


<button onclick="testing()"> 클릭하세요 </button>
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>
<p id="demo1"> </p>
<p id="demo2"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    var classList = getClasses( tag ); 
    var check1 = classList.contains( "anotherStyle" ); 
    document.getElementById( "demo1" ).innerHTML = check1; 
    var check2 = classList.contains( "someClass" ); 
    document.getElementById( "demo2" ).innerHTML = check2; 
} 
</script>


<button onclick="testing()"> 클릭하세요 </button>
<div id="myDiv" class="mystyle anotherStyle lastStyle"> 예문용 태그 </div>
<p id="demo1"> </p>
<p id="demo2"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    var classList = tag.classList || getClasses( tag ); 
    var check1 = classList.contains( "anotherStyle" ); 
    document.getElementById( "demo1" ).innerHTML = check1; 
    var check2 = classList.contains( "someClass" ); 
    document.getElementById( "demo2" ).innerHTML = check2; 
    } 
} 
</script>


7. classList.add() & getClasses().add()

classList의 "add()"는, 태그에 새로운 "class"를 추가하고 싶을 때 사용된다.
추가할 "class"가 이미 들어있으면 그대로 두고, 없으면 추가된다.


<style type="text/css">
.mystyle { padding: 5px; border: 2px solid #c4d3e2; } 
.anotherStyle { text-align: center  } 
.thirdClass { border-color: red } 
</style>
예문용 태그


<div id="myDiv" class="mystyle anotherStyle"> 예문용 태그 </div>
<button onclick="testing()"> 클릭하세요 </button>
<p id="demo1"> </p>
<p id="demo2"> </p>
<p id="demo3"> </p>
<p id="demo4"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    if ( "classList" in tag ){ 
        var classList = tag.classList; 
        var length = classList.length; 
        document.getElementById( "demo1" ).innerHTML = classList; 
        document.getElementById( "demo2" ).innerHTML = length; 

        classList.add( "thirdClass", "anotherStyle" ); 

        document.getElementById( "demo3" ).innerHTML = classList; 
        document.getElementById( "demo4" ).innerHTML = length; 
    } 
} 
</script>


<div id="myDiv" class="mystyle anotherStyle"> 예문용 태그 </div>
<button onclick="testing()"> 클릭하세요 </button>
<p id="demo1"> </p>
<p id="demo2"> </p>
<p id="demo3"> </p>
<p id="demo4"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    var classList = getClasses( tag ); 
    var length = classList.length; 
    document.getElementById( "demo1" ).innerHTML = classList; 
    document.getElementById( "demo2" ).innerHTML = length; 

    classList.add( "thirdClass", "anotherStyle" ); 

    document.getElementById( "demo3" ).innerHTML = classList; 
    document.getElementById( "demo4" ).innerHTML = length; 
} 
</script>
<div id="myDiv" class="mystyle anotherStyle"> 예문용 태그 </div>
<button onclick="testing()"> 클릭하세요 </button>
<p id="demo1"> </p>
<p id="demo2"> </p>
<p id="demo3"> </p>
<p id="demo4"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    var classList = getClasses( tag ); 
    var length = classList.length; 
    document.getElementById( "demo1" ).innerHTML = classList; 
    document.getElementById( "demo2" ).innerHTML = length; 

    classList.add( "thirdClass", "anotherStyle" ); 

    length = classList.length; 
    document.getElementById( "demo3" ).innerHTML = classList; 
    document.getElementById( "demo4" ).innerHTML = length; 
} 
</script>


<div id="myDiv" class="mystyle anotherStyle"> 예문용 태그 </div>
<button onclick="testing()"> 클릭하세요 </button>
<p id="demo1"> </p>
<p id="demo2"> </p>
<p id="demo3"> </p>
<p id="demo4"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    var classList = tag.classList || getClasses( tag ); 
    var string = classList.toString(); 
    var length = classList.length; 
    document.getElementById( "demo1" ).innerHTML = string; 
    document.getElementById( "demo2" ).innerHTML = length; 

    classList.add( "thirdClass", "anotherStyle" ); 

    string = classList.toString(); 
    length = classList.length; 
    document.getElementById( "demo3" ).innerHTML = string; 
    document.getElementById( "demo4" ).innerHTML = length; 
} 
</script>


8. classList.remove() & getClasses().remove()

classList의 "remove()"는,
태그의 "class"에 들어있는 것들 중에서, 원하는 항목을 삭제하고 싶을 때 사용한다.


<div id="myDiv" class="mystyle anotherStyle"> 예문용 태그 </div>
<button onclick="testing()"> 클릭하세요 </button>
<p id="demo1"> </p>
<p id="demo2"> </p>
<p id="demo3"> </p>
<p id="demo4"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    if ( "classList" in tag ){ 
        var classList = tag.classList; 
        var length = classList.length; 
        document.getElementById( "demo1" ).innerHTML = classList; 
        document.getElementById( "demo2" ).innerHTML = length; 

        classList.remove( "thirdClass", "anotherStyle" ); 

        document.getElementById( "demo3" ).innerHTML = classList; 
        document.getElementById( "demo4" ).innerHTML = length; 
    } 
} 
</script>


<div id="myDiv" class="mystyle anotherStyle"> 예문용 태그 </div>
<button onclick="testing()"> 클릭하세요 </button>
<p id="demo1"> </p>
<p id="demo2"> </p>
<p id="demo3"> </p>
<p id="demo4"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    var classList = getClasses( tag ); 
    var length = classList.length; 
    document.getElementById( "demo1" ).innerHTML = classList; 
    document.getElementById( "demo2" ).innerHTML = length; 

    classList.remove( "thirdClass", "anotherStyle" ); 

    document.getElementById( "demo3" ).innerHTML = classList; 
    document.getElementById( "demo4" ).innerHTML = length; 
} 
</script>
<div id="myDiv" class="mystyle anotherStyle"> 예문용 태그 </div>
<button onclick="testing()"> 클릭하세요 </button>
<p id="demo1"> </p>
<p id="demo2"> </p>
<p id="demo3"> </p>
<p id="demo4"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    var classList = getClasses( tag ); 
    var length = classList.length; 
    document.getElementById( "demo1" ).innerHTML = classList; 
    document.getElementById( "demo2" ).innerHTML = length; 

    classList.remove( "thirdClass", "anotherStyle" ); 

    length = classList.length; 
    document.getElementById( "demo3" ).innerHTML = classList; 
    document.getElementById( "demo4" ).innerHTML = length; 
} 
</script>


<div id="myDiv" class="mystyle anotherStyle"> 예문용 태그 </div>
<button onclick="testing()"> 클릭하세요 </button>
<p id="demo1"> </p>
<p id="demo2"> </p>
<p id="demo3"> </p>
<p id="demo4"> </p>

<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myDiv" ); 
    var classList = tag.classList || getClasses( tag ); 
    var string = classList.toString(); 
    var length = classList.length; 
    document.getElementById( "demo1" ).innerHTML = string; 
    document.getElementById( "demo2" ).innerHTML = length; 

    classList.remove( "thirdClass", "anotherStyle" ); 

    string = classList.toString(); 
    length = classList.length; 
    document.getElementById( "demo3" ).innerHTML = string; 
    document.getElementById( "demo4" ).innerHTML = length; 
} 
</script>


9. classList.toggle() & getClasses().toggle()

classList의 "toggle()" 함수는 조금 독특하다.
toggle()의 괄호 안에 넣어준 "class"에 대해서,
태그의 "class" 안에 그 class가 이미 들어있다면, 삭제하고
그렇지 않으면 추가한다.


아래의 예문에서는,
버튼을 클릭할 때마다, <p> 태그의 "class"가 바뀔 것이다.


<style type="text/css">
.hide {  display: none;  }
</style>

예문용 태그


<p id="myP"> 예문용 태그 </p>
<button onclick="testing()"> 클릭하세요 </button>
<script type="text/javascript">
function testing() { 
    var tag = document.getElementById( "myP" ); 
    if ( "classList" in tag ){ 
        var classList = tag.classList; 
        classList.toggle( "hide" ); 
    } 
} 
</script>

"toggle"이라는 단어에는, 무엇인가를 "켰다 껐다 한다(on/off)"이라는 뜻이 들어있다.

toggle() 함수가 실행된 후의 결과값은, 'true' 또는 'false' 이다.
on = true : 켜짐. 추가됨.
off = false : 꺼짐. 삭제됨.


  • HTML
  • CSS
  • JavaScript

 

<ul id="myList">
        <li> HTML </li>
        <li> CSS </li>
        <li> JavaScript </li>
</ul>
<p id="demo"></p>
<button id="myBtn" onclick="testing()"> 숨기기 </button>
<script type="text/javascript">
function testing (){ 
    var tag = document.getElementById( "myList" ); 
    if ( "classList" in tag ){ 
        var classList = tag.classList; 
        var isOn = classList.toggle( "hide" ); 
        var text = ( isOn ) ? "보이기" : "숨기기"; 
        document.getElementById( "myBtn" ).innerHTML = text; 
        document.getElementById( "demo" ).innerHTML = isOn; 
    } 
} 
</script>


  • HTML
  • CSS
  • JavaScript

 

<ul id="myList">
        <li> HTML </li>
        <li> CSS </li>
        <li> JavaScript </li>
</ul>
<p id="demo"></p>
<button id="myBtn" onclick="testing()"> 숨기기 </button>
<script type="text/javascript">
function testing() { 
    var tag = document.getElementById( "myList" ); 
    var classList = getClasses( tag ); 
    var isOn = classList.toggle( "hide" ); 
    var text = ( isOn ) ? "보이기" : "숨기기"; 
    document.getElementById( "myBtn" ).innerHTML = text; 
    document.getElementById( "demo" ).innerHTML = isOn; 
} 
</script>


  • HTML
  • CSS
  • JavaScript

 

<ul id="myList">
        <li> HTML </li>
        <li> CSS </li>
        <li> JavaScript </li>
</ul>
<p id="demo"></p>
<button id="myBtn" onclick="testing()"> 숨기기 </button>
<script type="text/javascript">
function testing() { 
    var tag = document.getElementById( "myList" ); 
    var classList = tag.classList || getClasses( tag ); 
    var isOn = classList.toggle( "hide" ); 
    var text = ( isOn ) ? "보이기" : "숨기기"; 
    document.getElementById( "myBtn" ).innerHTML = text; 
    document.getElementById( "demo" ).innerHTML = isOn; 
} 
</script>


toggle()의 괄호 안에, 추가로 'true' 또는 'false'를 넣어주면, 결과는 달라진다.

"class"의 존재 여부와 상관없이,
그 "class"를 강제로 끄거나 켜고 싶을 때, 이용하는 방법이다.

첫번째로 "class"의 이름을 넣어주고, 두번째로 "true 또는 false"를 넣어주면 된다.


예문용 태그

 

<p id="myP" class="mystyle"> 예문용 태그 <p>
<p id="demo"></p>
<button onclick="testing()"> 클릭하세요 </button>

<script type="text/javascript">
function testing() { 
    var tag = document.getElementById( "myP" ); 
    var classList = tag.classList || getClasses( tag ); 
    var result = classList.toggle( "lastStyle", true ); // 무조건 추가하기. 
    document.getElementById( "demo" ).innerHTML = result; 
} 
</script>

예문용 태그

 

<p id="myP" class="mystyle"> 예문용 태그 <p>
<p id="demo"></p>
<button onclick="testing()"> 클릭하세요 </button>

<script type="text/javascript">
function testing() { 
    var tag = document.getElementById( "myP" ); 
    var classList = tag.classList || getClasses( tag ); 
    var result = classList.toggle( "lastStyle", false ); // 무조건 삭제하기. 
    document.getElementById( "demo" ).innerHTML = result; 
} 
</script>


<p id="myP"> 예문용 태그 </p>
<button onclick="testing()"> 클릭하세요 </button> 
<p id="demo1"> </p>
<p id="demo2"> </p>

<p id="demo3"> </p>
<p id="demo4"> </p>

<script type="text/javascript">
function testing() { 
    var tag = document.getElementById( "myP" ); 
    var classList = tag.classList || getClasses( tag ); 
    var string = classList.toString(); 
    var length = classList.length; 
    document.getElementById( "demo1" ).innerHTML = string; 
    document.getElementById( "demo2" ).innerHTML = length; 

    classList.toggle( "lastStyle" ); 

    string = classList.toString(); 
    length = classList.length; 
    document.getElementById( "demo3" ).innerHTML = string; 
    document.getElementById( "demo4" ).innerHTML = length; 
} 
</script>


10. classList를 사용할 때에, 오류가 나는 경우

classList와 관련된 위의 함수들을 사용할 때에,
그 함수에 넣어주는 "class"의 이름으로,
아무 내용이 없는 빈 문자열( "" )이나,
공백문자(띄어쓰기)가 들어있는 문자열을 넣어주면,
함수가 제대로 실행되지 않고서, 오류가 발생한다.


<div id="myDiv" class="mystyle anotherStyle thirdClass"> 예문용 태그 </div>
 
<button onclick="example()"> 클릭하세요 </button>

<p id="demo1"> </p>

<script type="text/javascript">
function example (){ 

   var classList = myDiv.classList; 

   demo1.innerHTML = classList.contains( " anotherStyle " ); 
} 
</script>
<button onclick="example()"> 클릭하세요 </button>

<p id="demo2"> </p>

<script type="text/javascript">
function example (){ 

   var classList = getClasses( myDiv ); 

   demo2.innerHTML = classList.contains( " anotherStyle " ); 
} 
</script>
 
<button onclick="example()"> 클릭하세요 </button>

<p id="demo3"> </p>

<script type="text/javascript">
function example (){ 

    var classList = myDiv.classList; 

    try {  classList.add( "" );  } 

    catch ( error ){  demo3.innerHTML = error.message;  } 
} 
</script>
<button onclick="example()"> 클릭하세요 </button>

<p id="demo4"> </p>

<script type="text/javascript">
function example (){ 

    var classList = getClasses( myDiv ); 

    try {  classList.add( "" );  } 

    catch ( error ){  demo4.innerHTML = error.message;  } 
} 
</script>


w3schools.com의 페이지에서, Try it Yourself » 이라는 버튼을 클릭하면, 위 내용을 직접 테스트해볼 수 있다.




이 내용이 도움이 되셨다면, 아래의 하트 버튼을 눌러주세요 *^^*