How can I change an element's class with JavaScript? Ask Question

How can I change an element's class with JavaScript? Ask Question

How can I change the class of an HTML element in response to an onclick or any other events using JavaScript?

ベストアンサー1

Modern HTML5 Techniques for changing classes

Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library:

document.getElementById("MyElement").classList.add('MyClass');

document.getElementById("MyElement").classList.remove('MyClass');

if ( document.getElementById("MyElement").classList.contains('MyClass') )

document.getElementById("MyElement").classList.toggle('MyClass');

Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. It is, though, getting more and more supported.

Simple cross-browser solution

The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer.

To change all classes for an element:

To replace all existing classes with one or more new classes, set the className attribute:

document.getElementById("MyElement").className = "MyClass";

(You can use a space-delimited list to apply multiple classes.)

To add an additional class to an element:

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so:

document.getElementById("MyElement").className += " MyClass";

To remove a class from an element:

To remove a single class to an element, without affecting other potential classes, a simple regex replace is required:

document.getElementById("MyElement").className =
   document.getElementById("MyElement").className.replace
      ( /(?:^|\s)MyClass(?!\S)/g , '' )
/* Code wrapped for readability - above is all one statement */

An explanation of this regex is as follows:

(?:^|\s) # Match the start of the string or any single whitespace character

MyClass  # The literal text for the classname to remove

(?!\S)   # Negative lookahead to verify the above is the whole classname
         # Ensures there is no non-space character following
         # (i.e. must be the end of the string or space)

The g flag tells the replace to repeat as required, in case the class name has been added multiple times.

To check if a class is already applied to an element:

The same regex used above for removing a class can also be used as a check as to whether a particular class exists:

if ( document.getElementById("MyElement").className.match(/(?:^|\s)MyClass(?!\S)/) )

### Assigning these actions to onClick events:

Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onClick="this.className+=' MyClass'") this is not recommended behavior. Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic.

The first step to achieving this is by creating a function, and calling the function in the onClick attribute, for example:

<script type="text/javascript">
    function changeClass(){
        // Code examples from above
    }
</script>
...
<button onClick="changeClass()">My Button</button>

(It is not required to have this code in script tags, this is simply for the brevity of example, and including the JavaScript in a distinct file may be more appropriate.)

The second step is to move the onClick event out of the HTML and into JavaScript, for example using addEventListener

<script type="text/javascript">
    function changeClass(){
        // Code examples from above
    }

    window.onload = function(){
        document.getElementById("MyElement").addEventListener( 'click', changeClass);
    }
</script>
...
<button id="MyElement">My Button</button>

(Note that the window.onload part is required so that the contents of that function are executed after the HTML has finished loading - without this, the MyElement might not exist when the JavaScript code is called, so that line would fail.)


JavaScript Frameworks and Libraries

上記のコードはすべて標準の JavaScript で書かれていますが、一般的なタスクを簡素化したり、コードの作成時には思いつかなかったバグやエッジ ケースの修正の恩恵を受けたりするために、フレームワークまたはライブラリを使用するのが一般的です。

単にクラスを変更するためだけに約 50 KB のフレームワークを追加するのはやりすぎだと考える人もいますが、大量の JavaScript 作業や、異常なクロスブラウザー動作が発生する可能性がある作業を行う場合は、検討する価値は十分にあります。

(大まかに言うと、ライブラリは特定のタスク用に設計されたツールのセットであり、フレームワークには通常複数のライブラリが含まれており、一連のタスクを完全に実行します。)

上記の例は、以下を使用して再現されています。jQueryおそらく最もよく使われる JavaScript ライブラリです (ただし、調査する価値のあるライブラリは他にもあります)。

($ここには jQuery オブジェクトがあることに注意してください。)

jQuery でクラスを変更する:

$('#MyElement').addClass('MyClass');

$('#MyElement').removeClass('MyClass');

if ( $('#MyElement').hasClass('MyClass') )

さらに、jQuery では、適用されないクラスを追加したり、適用されるクラスを削除したりするためのショートカットが提供されます。

$('#MyElement').toggleClass('MyClass');

### jQuery を使用してクリック イベントに関数を割り当てる:
$('#MyElement').click(changeClass);

または、ID を必要とせずに:

$(':button:contains(My Button)').click(changeClass);

おすすめ記事