JavaScript/jQuery

【jQuery/Traversing】addBack([selector])

1Q74 2023. 4. 13. 15:36

1. Description

.addBack([selector])
selector에 의해서 필터링 된 Element들 중에서, 현재 선택한 Element의 스택상에 이전 Element를 추가한다.

2. Example

#1버튼을 클릭하면 <ol>Element와 li:eq(2)를 선택하여 border스타일을 변경한다. 버튼을 클릭할 때마다 해당 스타일이 토글된다.


[1q74.tistory.com] javascript/jquery/traversing/addBack([selector])
  1. Google
  2. Amazon
  3. Facebook
    1. Tesla
    2. Twitter
    3. Netflex
  4. Apple


3. Code

더보기
<!-- ---------------------------------------------------------
  --
  -- Author: 1q74.tistory.com
  --
  --------------------------------------------------------- -->
<!doctype html>
<html lang="ko">
<head>
<meta charset="utf-8">
<title>[1q74.tistory.com] javascript/jquery/traversing/addBack([selector])</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head>
<body>

	<div name="_1q74-ex-root">
		<div name="_1q74-ex-1">
			<ol name="bigtech">
				<li>Google</li>
				<li>Amazon</li>
				<li>Facebook</li>
				<ol>
					<li>Tesla</li>
					<li>Twitter</li>
					<li>Netflex</li>
				</ol>
				<li>Apple</li>
			</ol>
		</div>

		<br/>

		<div name="_1q74-ex-bottom">
			<table border="1">
				<tr>
					<td colspan="2">
						<button name="btn-find">
							#1. Click Me
						</button>
					</td>
				</tr>
			</table>
		</div>
	</div>

<script>
//
// _1q74 is a Namespace for preventing confliction of variable.
// It has not mean specially.
//
var _1q74 = {};
_1q74.example = {
	/////////////////////////////////////////////////////////////////
	//
	// Example container
	//
	/////////////////////////////////////////////////////////////////
	container: $("[name='_1q74-ex-1']"),

	/////////////////////////////////////////////////////////////////
	//
	// Execute example
	//
	/////////////////////////////////////////////////////////////////
	execute: function() {
		const _this = this;
		const btnFind = $("[name='btn-find']");
		const bigtech = _this.container.find("[name='bigtech']");
		const elements = bigtech.find("ol").find("li:eq(2)").addBack();

		btnFind.click("click", function() {
			if(!elements.is("[style]")) {
				elements.css("border", "1px dotted lightgreen");
			} else {
				elements.removeAttr("style");
			}
		});
	},
}

_1q74.example.execute();
</script>
<style>
[name="_1q74-ex-root"] {
	min-height: 200px;
}

[name="_1q74-ex-1"] {
	min-height: 170px;
}

[name="_1q74-ex-bottom"] {
	min-height: 150px;
}

[name="_1q74-ex-1"] td {
	min-width: 30px;
	min-height: 30px;
	width: 120px;
}

[name="_1q74-ex-bottom"] tbody {
	max-width: 400px;
}

[name="_1q74-ex-bottom"] td {
	width: 300px;
}

[name|="_1q74-ex"] button {
	background: lightgray;
	border: 5px outset;
	min-height: 40px;
	width: 100%;
}

[name|="_1q74-ex"] button:active {
	border: 5px inset;
	min-height: 40px;
	width: 100%;
}
</style>

</body>
</html>

4. File

[javascript][jquery][traversing]addBack.html
0.00MB


5. Reference

https://api.jquery.com/addBack/