LoginSignup
0
0

More than 1 year has passed since last update.

javaScript96_DOM操作

Last updated at Posted at 2022-02-21

UdemyでJavaScriptをとことんやってみよう【超初心者から脱初心者へレベルアップ】の講座を勉強しているため、メモをこちらに残します。

DOMを操作するには、よくある流れは以下になります。

  1. 変化させたい要素を指定する。
  2. イベントを指定する。
  3. 処理を書く。

イベントを指定する方法は下記3つあります。
イベントハンドラー(関数) (イベントは一つのみ指定できる)

  1. document.getElementById().onclick = function();

イベントリスナー(イベントは追加、複数登録できる)
3. el.addEventListener('click',callback);

1つ目の例:(HTMLタグの中で設定する)

<body>
   <div id="test"></div>
   <button id="target" onclick="change_color()">押してね</button>
   
<script>
    function change_color(){
        const test = document.getElementById("test");
        test.textContent = "テスト";
    }
</script>
</body>

2つ目の例:(JSのelement値の中で設定)

<body>
   <div id="test"></div>
   <button id="target">押してね</button>
   
<script>
    // JSの中で設定する element.onclick
    document.getElementById("target").onclick = function(){
        const test = document.getElementById("test");
        test.textContent = "テスト";

    }

</script>
</body>

3つ目の例: イベントリスナー

<body>
   <div id="test"></div>
   <button id="target">押してね</button>
   
<script>

    // イベントリスナー
    const target = document.getElementById("target");
    target.addEventListener('click',()=>{
        const test = document.getElementById("test");
        test.textContent = "テスト";
    });

</script>
</body>

引数にeを入れると、eventオブジェクトを取得することができる

  target.addEventListener('click',(e) => {
        console.log(e);

ハブリングを止める(イベントの連鎖を止める)には
image.png

e.stopPropagation();

<body>
  <div id="div1">div1
    <div id="div2">div2
        <div id="div3">div3</div>
    </div>
  </div>
<script>
const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
const div3 = document.getElementById("div3");

div1.addEventListener('click',()=>alert("div1です"));
div2.addEventListener('click',()=>alert("div2です"));
div3.addEventListener('click',(e)=>
// e.stopPropagation(); イベントの伝播を止める
{   e.stopPropagation();
    alert("div3です")
});
</script>
</body>

(aタグ)リンクが実行されるのを止める
e.prevendDefault();

DOMの中に要素の子ノードを取得するには、
下記4つの方法があります。

  1. getElementsByTagName()
    -メソッド: 指定ノードの子ノードを返す

  2. childNodes
    -属性: 現在ノードの全ての子ノード

  3. firstChild
    -属性: 現在ノードの初めての子ノード

  4. lastChild
    -属性: 現在ノードの最後の子ノード

  5. getElementsByTagName()
    image.png

  6. childNodes
    image.png

  7. firstChild,lastChild属性
    image.png
    hmtlファイル:
    image.png

0
0
0

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
0
0