【jQuery】find()とfilter()の違い

サンプル

find()とfilter()の違い
find()
子要素を対象に絞り込みを行う
→ $(‘div’).find(‘hoge’) = $(‘div .hoge’)
filter()
当該要素を対象に絞り込みを行う
→ $(‘div’).filter(‘hoge’) = $(‘div.hoge’)

ソースコード

HTML




※Console参照


find()で取得できる

filter()で取得できる
CSS


body {
    margin: 20px;
}

button {
    border: none;  /* 枠線を消す */
    outline: none; /* クリックしたときに表示される枠線を消す */

    width: 100px;
    height: 50px;
    background-color: #eee;

    cursor: pointer;
}
jQuery


$(function(){
    /*
        find()
            $('div .text')と同じ
    */
    $('button.find').click(function() {
        text = $('div').find('.text').text();
        console.log(text);
    });


    /*
        filter()
            $('div.text')と同じ
    */
    $('button.filter').click(function() {
        text = $('div').filter('.text').text();
        console.log(text);
    });
});

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です