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?

More than 1 year has passed since last update.

ECMAscript以前のjQueryのappendを書くときにメソッドチェーンでの階層構造っぽい書き方

Last updated at Posted at 2022-08-21

備忘録として記載しておきます。
jQueryでappendを書くときに、こんな書き方をしていませんか?
例えば出力したいHTMLは以下の通りであるとき、

output.html
<div class="hoge">
    <img class="hoge" src="hoge.png">
    <div class="hogehoge">
        <img src="hogehoge.png">
    </div>
    <div class="piyo">
        <button type="button" onclick="piyoFunction()">
            <img src="piyo.png">
        </button>
    </div>
</div>

jQuery

before.js
$('#hoge').append('<div class="hoge"><img class="hoge" src="hoge.png"><div class="hogehoge"><img src="hogehoge.png"></div><div class="piyo"><button type="button" onclick="piyoFunction()" tabindex="0"><img src="piyo.png"></button></div></div>');

これだと何度も修正を入れるようなコードだと要素がどこにあるのか分かりづらいですね。
そこで、以下のように書き直してみます。

after.js
$('#hoge').append(
    $('<div>',{
        class:'hoge'
    }).append(
        $('<img>',{
            class:'hoge',
            src:'hoge.png'
        })
    ).append(
        $('<div>',{
            class:'hogehoge'
        }).append(
            $('<img>',{
                src:'hogehoge.png'
            })
        )
    ).append(
        $('<div>',{
            class:'piyo'
        }).append(
            $('<button>',{
                type:'button',
                onclick:'piyoFunction()'
            }).append(
                $('<img>',{
                    src: 'piyo.png'
                })
            )
        )
    )
);

クラス、タグ、type、onclick、srcなど、分けて書くことで見やすくなりました。
注意点としては、ここではappendを7回行っていますが、DOM操作を何度も行うのは速度低下の原因になるので、
ループなどでは可能な限りappendは少ない回数で済ませることができればそれに越したことはないです。

高速化.js
var html = '';
for(var i=0; i<500; i++){
  html += '<div></div>';
}
$('#hogehoge').append(html);

引用元:「高速化メモ JavaScript編」
 →500個のdivを変数に入れてappendメソッドを実行する
https://qiita.com/redamoon/items/1c38ee93834588e3c4ff#500%E5%80%8B%E3%81%AEdiv%E3%82%92%E5%A4%89%E6%95%B0%E3%81%AB%E5%85%A5%E3%82%8C%E3%81%A6append%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E3%82%92%E5%AE%9F%E8%A1%8C%E3%81%99%E3%82%8B

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?