3
2

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 5 years have passed since last update.

jQueryのsibilingsの子要素はchildrenで取る

Posted at

はじめに

  • JQuerysiblingsの子要素の取得時にハマったので同じ問題でハマっている人がいるかもしれないので共有の意味で記事にしたもの。

コード

index.html
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    </head>

    <body>
        <div id="div1">
            <span id="span1">hoge</span>
        </div>
        <div id="div2">
            <span id="span2">hoge</span>
        </div>

        <script type="text/javascript" src="siblings.js"></script>
    </body>
</html>
siblings.js
$(function(){
  console.log($('div#div1').siblings('div#div2').html());
  console.log($('div#div1').siblings('div#div2').children('span#span2').html());
  console.log($('div#div1').siblings('div#div2 > span#span2').html());
});
  • htmlの方は特に何も難しいことはしていなく、divの中にspanが入ったものが2つ並んでいるだけ
  • jsの方はdiv1の兄弟要素であるdiv2を取得
  • その中の子要素であるspanに関して2通りの取り方を試みている(children>

結果

スクリーンショット 2015-09-29 9.19.33.png

考察

焦点となるのは以下の2つの記述

  • $('div#div1').siblings('div#div2').children('span#span2')
  • $('div#div1').siblings('div#div2 > span#span2')

一見どちらも「div1の兄弟要素div2の子要素span2」を取得しそうに見えるが、実は下の記述ではしない。
下の記述では「div1の兄弟要素として『div2の子要素span2』」を取得しに行こうとする。
「div2の子要素span2」は「div1の兄弟要素」ではないので取得できない。
という現象が起きている(と思う)

まとめ

今回たまたまsiblingsでハマったことですが、恐らくchildrenparent等でも起きうることだと思います。
>childrenの使い分けに気をつけましょう。

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?