jquery addBackメソッドを使って取得した要素を取得する

jqueryでaddBackメソッドを使うと「指定して取得した要素とその1つ前の要素」を取得することができます。ここでは、addBackメソッドを実際に使用したサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
※windows10にApacheのインストールはこちら
addBack使い方
ボタンをクリックして、nextメソッドで取得した「td」タグのid「test3」とその1つ前の「td」タグのid「test2」のフォントカラーを変更するサンプルコードとなります。
<!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: 200px;
display: flex;
flex-direction: column;
align-items: center;
font-size: 30px;
}
</style>
<script>
$(function(){
$('.btn').click(function(){
$("#test2").next().addBack().css("color", "#3eb810");
});
});
</script>
<body>
<div class="container">
<table class="table">
<thead class="table-striped">
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
<th scope="col">age</th>
<th scope="col">email</th>
<th scope="col">address</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row" id="test1">1</th>
<td id="test2">Mark</td>
<td id="test3">Otto</td>
<td id="test4">@mdo</td>
<td id="test5">20</td>
<td id="test6">info@mebee.info</td>
<td id="test7">japan</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-raised btn-warning">変換する</button>
</div>
</body>
</html>
実行結果を見ると、「td」タグのid「test2」と「td」タグのid「test3」のフォントカラーが変更されることが確認できます。

-
前の記事
React.js ライブラリ「react-notification-timeline」を使って通知機能を実装する 2020.11.13
-
次の記事
javascript 配列の値を全てに同じ変更をして新しい配列を作成する 2020.11.14
コメントを書く