jquery closestメソッドを使って指定した要素の一番近い親要素のIDを取得する

jquery closestメソッドを使って指定した要素の一番近い親要素のIDを取得する

jqueryでclosestメソッドを使うと指定した要素の一番近い親要素のIDを取得することができます。ここでは、親要素を取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43

※windows10にApacheのインストールはこちら

closest使い方

ボタンをクリックして、親要素divを指定してidを取得するサンプルコードです。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet" href="https://unpkg.com/bootstrap-material-design@4.1.1/dist/css/bootstrap-material-design.min.css" integrity="sha384-wXznGJNEXNG1NFsbm0ugrLFMQPWswR3lds2VeinahP8N0zJw9VWSopbjv2x7WCvX" crossorigin="anonymous">
  <script src="http://code.jquery.com/jquery-3.5.1.min.js"></script>  
</head>
<style>
.container {
  margin: 0 auto;
  margin-top: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 30px;
}
</style>
<script>
$(function(){
  $('.btn').click(function(){
    var idname = $(".alert-link").closest("div").attr("id");
    $('.alert-warning').text(idname);
  });
});

</script>
<body>
  <div class="container">
    
    <div class="alert alert-info" role="alert" id="test">
      親要素親要素<a href="#" class="alert-link">子要素</a>親要素親要素親要素
    </div>

    <div class="alert alert-warning" role="alert">
      取得したIDを表示します
    </div>
    
    <button type="button" class="btn btn-outline-success">ID取得</button>
    
  </div>
</body>
</html>

ボタンをクリックすると、指定した親要素である「div」のidが取得されます。