Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript入門メモ

Posted at

以下の入門講座本にて個人的に勉強になったJavaScriptのメソッドや記法を纏めてみました。

適宜進行に応じて増やしていきます。

1.要素の取得

document.querySelector('セレクター');

// 例
document.querySelector('#test'); // id指定
document.querySelector('.test'); // class指定
document.querySelector('h1'); //タグ指定

documentオブジェクト内の特定セレクター(括弧内)を持つ要素を取得する。
複数存在するセレクターの場合、最初の要素を取得する。
指定したセレクターを全て指定する場合は、querySelectorAll('')を用いる。

2.要素内のテキストの取得・書き換え

document.querySelector('セレクター').textContent;

//例
// h1タグのテキストを'test'というテキストに書き換える場合
document.querySelector('h1').textContent = 'test';

特定セレクター内のテキストを取得する。
取得の他にも例題のようにテキストを上書きすることも出来る。

3.テンプレート文字列

` ` // バックフォートで囲む
// 例
// コンソールログにh1内のテキストを出力する。
console.log(`h1タグのテキストは、${document.querySelector('h1').textContent}`);

テンプレート文字列では、文字列とJavaScriptを同時に使用出来る。
「'文字列' + JavaScript」と書かずに済むため、スムーズに書くことが出来る。
テンプレート文字列内にてJavaScriptを使用する場合は、${}で囲むと使用を可能になる。

4. 定数と変数

//変数 読み・書き可能な値として保持
let 変数名 = 代入したい値;

//定数 読み取り専用(上書き不可)の値として保持
const 定数名 = 代入したい値;

// 例1 変数
let a = 'testA'; // 変数aへ'testA'という文字列を代入する
a = 12345;       // 変数aへ12345という数値を代入する
console.log(b);  // 最後に代入した12345という数値が出力される

// 例2 定数
const b = 'testB'; // 定数bへ'testB'という文字列を代入する
b = 12345;         // 定数bへ12345という数値を代入する
console.log(b);    // 「TypeError: Assignment to constant variable」という定数上書き時に発生するエラーが表示される。

定数の場合、途中で値の変わる可能性がない為、教材上では主にconstをメインとして採用されていた。
コード内で誤って値を代入するミスを未然に防げるため、constを積極的に使用していきたい。

5. イベント

要素.addEventListener('イベントのタイプ', () => {}); // 無記名関数による記法
要素.addEventListener('イベントのタイプ', 関数);     // 関数を用いた記法

// 例1
// h1タグをクリックした際、コンソールへの出力するイベントが発動する
document.querySelector('h1').addEventListener('click', () => {
  console.log('クリックしました');
});

// 例2
// まずは関数を設定する。
const test = () => {
  console.log('クリックしました');
};
// h1タグをクリックした際、先ほどの関数が呼び出されイベントとして発動する
document.querySelector('h1').addEventListener('click', test);

イベントのきっかけとなるタイプはclickの他にもinput keyup mouseup等複数のが存在する。

6.スタイルの変更

要素.style.cssのプロパティ値 = ;

// 例
// h1タグのテキストカラーを#0bd(青)へ変更する。
document.querySelector('h1').style.color = '#0bd';
// 例2
// divタグの背景色を#0bd(青)へ変更する。
document.querySelector('div').style.backgroundColor = '#0bd'; 

CSSのプロパティ値にハイフンがある場合、ハイフンを取り除いたキャメルケースで指定する必要がある。
background-color → backgroundColor

7.クラスの付与

要素.classList.add('クラス名');
要素.classList.add('クラス名','クラス名'); // 複数のクラスを付与する場合

// 例
// pタグへtestクラスを付与する
p.classList.add('test');

8.クラスの削除

要素.classList.remove('クラス名');
要素.classList.remove('クラス名','クラス名'); // 複数のクラスを削除する場合

// 例
// pタグにあるtestクラスを削除する
p.classList.remove('test');

9.クラスの付け外し

要素.classList.toggle('クラス名'); 

// 例
// ボディタグに対してdarkクラスがなければ付与、あれば削除する
body.classList.toggle('dark'); 

ボタン等のクリックに合わせて使用しても良いかも。

10.文字数を数える

'文字列'.length;

//例
// h1タグの文字数を出力する。
console.log(document.querySelector('h1').textContent.length);

console.log('😀'.length); // 顔文字や一部漢字は正しい文字数としてカウントされない
console.log([...'😀'].length); // 対応策としてスプレッド演算子で正しい文字数に出来る

変な所があればコメントいただければと思います。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
roy0201

@roy0201(roy)

備忘録として残していきます。

Comments

roy0201
@roy0201(roy)

@shiracamus タグの追加有難うございます!

関連タグ追加(Web HTML DOM にも関連する記事なので) by shiracamus 2024/10/30 23:11

0
diywmk9
@diywmk9
// h1タグをクリックした際、先ほどの関数が呼び出されイベントとして発動する

この場合、h1タグをクリックイベント で、イベントの発生と実際の処理との関連付けイベントリスナー ということになります。
例えば、「ボタンがクリックされたら背景色を青くする」という一連の処理があった場合、イベントに当たるのは「ボタンをクリック」であり「背景色を青くする」ではない、ということです。


console.log([...'😀'].length); // 対応策としてスプレッド演算子で正しい文字数に出来る

サロゲートペアに関わる文字など、上記の方法ではうまくカウントできないものもあります。

console.log([...'葛󠄀'].length); // 2
console.log([...'👍🏻'].length); // 2
console.log([...'👨‍👧'].length); // 3
console.log([...'👨‍👦‍👦'].length); // 5
console.log([...'👩‍👩‍👦‍👦'].length); // 7

もちろん普通のString.lengthも駄目です。

console.log('葛󠄀'.length); // 3
console.log('👍🏻'.length); // 4
console.log('👨‍👧'.length); // 5
console.log('👨‍👦‍👦'.length); // 8
console.log('👩‍👩‍👦‍👦'.length); // 11

正確な文字数が必要な場合、Intl.Segmenter()が利用できます。

const spLength = str => [...new Intl.Segmenter('ja').segment(str)].length;
console.log(spLength('葛󠄀')); // 1
console.log(spLength('👍🏻')); // 1
console.log(spLength('👨‍👧')); // 1
console.log(spLength('👨‍👦‍👦')); // 1
console.log(spLength('👩‍👩‍👦‍👦')); // 1
0

Let's comment your feelings that are more than good

Qiita Conference 2024 Autumn will be held!: 11/14(Thu) - 11/15(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

Takahiro Anno, Masaki Fujimoto, Yukihiro Matsumoto(Matz), Shusaku Uesugi / Nicolas Ishihara(Vercel Inc.)

View event details

Being held Article posting campaign

0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address