LoginSignup
5

More than 5 years have passed since last update.

jQueryで自分以外の兄弟要素を取得する方法

Posted at

ことの背景

とある構築で、クリックされた要素以外の要素を取得する必要があり、かなり使いやすい実装があったのでメモ代わりにここに記す。

まずはHTMLファイルから

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>jqueryで自分以外の兄弟要素を取得する</title>
    <style>
        .red {
            background: red;
        }

        .blue {
            background: blue;
        }

        .Brother
        {
            display: flex;
        }

        .child1,
        .child2,
        .child3,
        .child4
        {
            display: block;
            width: 200px;
            height: 200px;
            line-height: 200px;
            text-align: center;
            border: 1px solid #ccc;
            margin: 10px;
        }
    </style>
</head>
<body>
<div class="Wrapper">
    <div class="Container">
        <div class="Contents">
            <ul class="Brother">
                <li class="child1">Child1</li>
                <li class="child2">Child2</li>
                <li class="child3">Child3</li>
                <li class="child4">Child4</li>
            </ul>
        </div>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="app.js"></script>
</body>
</html>

注目ポイントは以下の箇所。

<ul class="Brother">
                <li class="child1">Child1</li>
                <li class="child2">Child2</li>
                <li class="child3">Child3</li>
                <li class="child4">Child4</li>
            </ul>

このBrotherを親に持つliのどれかの要素がクリックされた際に、自分以外の要素を取得する。
child1クラスをもつ<li>をクリックしたら、child2,child3,child4クラスの<li>を取得してくる。
その処理は以下。

app.js
$(function () {

    $('li').on('click', function () {
        $(this).siblings().css('background','red');
    });
});

注目は<$(this).siblings().css('background','red');>の記述。
siblings()関数は、各要素の兄弟要素を全て返してくれるので、クリックした要素の兄弟要素を返してくれた。

参考

siblings(expr) - jQuery 日本語リファレンス

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
5