teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

jQueryとの相対性を追記

2019/12/19 02:19

投稿

thyda.eiqau
thyda.eiqau

スコア2982

answer CHANGED
@@ -1,29 +1,24 @@
1
1
  jQueryではクラスをつけたり外したりしているのは `$(this)` と `$('#list')` ですが、これらはVanilla JSではどこに行ったのですか?
2
2
 
3
3
  ```js
4
- // jQuery
4
+ // ↓ $(function() { に相当
5
- $(function() {
5
+ window.addEventListener('DOMContentLoaded', function() {
6
- $('#trigger').on('click', function() {
6
+ // ↓ $('#trigger').on('click', function() { に相当
7
+ ducument.querySelector('#trigger').addEventListener('click', function() {
8
+ // ↓ $(this) に相当
9
+ const _this = event.currentTarget;
10
+ // ↓ $('#list') に相当
11
+ const ducument.querySelector('#list');
7
- if($(this).hasClass('active')) {
12
+ // ↓ if($(this).hasClass('active')) { に相当
13
+ if(_this.classList.contains('active')) {
14
+ // ↓ .removeClass(className) に相当
8
- $(this).removeClass('active');
15
+ _this.classList.remove('active');
9
- $('#list').removeClass('open');
16
+ list.classList.remove('open');
10
17
  } else {
18
+ // ↓ .addClass(className) に相当
11
- $(this).addClass('active');
19
+ _this.classList.add('active');
12
- $('#list').addClass('open');
20
+ list.classList.add('open');
13
21
  }
14
22
  });
15
23
  });
16
-
17
- // Vanilla
18
- document.getElementById('trigger').onclick = function(event) {
19
- const _this = event.currentTarget;
20
- const list = document.getElementById('list');
21
- if(_this.classList.contains('active')) {
22
- _this.classList.remove('active');
23
- list.classList.remove('open');
24
- } else {
25
- _this.classList.add('active');
26
- list.classList.add('open');
27
- }
28
- };
29
24
  ```