JavaScript/jQuery

【jQuery/Selector #16】Descendant Selector (“ancestor descendant”)

1Q74 2023. 2. 22. 16:12

1. Description

부모Element 하위에 있는 Element들 중, 매칭되는 모든 Element들을 찾는다.


2. Example

$("[name='bigtech'] li") Selector을 사용하여, bigtech하위에 있는 모든 <li>태그를 찾는다.


[1q74.tistory.com] javascript/jquery/selector/descendant
  1. Google
  2. Amazon
  3. Facebook
    1. Tesla
    2. Twitter
    3. Netflex
  4. Apple
  5. And my future company


[HTML Code]
[//HTML Code]

3. Code

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

	<div name="_1q74-example-root">
		<div name="_1q74-example-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>
				<li>And my future company</li>
			</ol>
		</div>

		<div name="_1q74-example-bottom">
			<br/>
			<button name="btn-find">#1. $("[name='bigtech'] li")</button>
		</div>
	</div>

	<hr/>
	<h5>[HTML Code]</h5>
	<div name="_1q74-source">
	</div>
	<h5>[//HTML Code]</h5>

<script>
const btnFind = $("[name='btn-find']");

btnFind.click(function() {
	const bigtech = $("[name='bigtech'] li");
	
	bigtech.each(function(index, el) {
		const element = $(el);
		const checkMark = "✔";
		const text = element.text();
		const isExistCheckMark = (text.indexOf(checkMark) > -1);

		if(!isExistCheckMark) {
			element.text(text + " " + checkMark);
		} else {
			element.text(text.replace(" " + checkMark, ""));
		}
	});
});

// ------------------------------------------------------
// 소스출력
// ------------------------------------------------------
var textSource = $("[name='_1q74-source']");
var exampleHtml = $("[name='_1q74-example-root']").html();
var specialCharLines = textSource.text(exampleHtml).html().split("\n");

textSource.html(specialCharLines.join("<br/>").replaceAll("\t", "&nbsp;&nbsp;"));
</script>
<style>
[name|="_1q74-example"] button
,[name="_1q74-source"] button {
	background: lightgray;
	border: 5px outset;
	min-height: 30px;
}

[name|="_1q74-example"] button:active
,[name="_1q74-source"] button:active {
	border: 2px inset;
	min-height: 30px;
}
</style>

</body>
</html>

4. File

[javascript][jquery][selector]descendant.html
0.00MB


5. Reference

https://api.jquery.com/descendant-selector/