JavaScript/jQuery

【jQuery/Selector #13】Child Selector (“parent > child”)

1Q74 2023. 2. 22. 12:13

1. Description

부모Element의 한 단계 아래의 Element들만 찾는다(두 단계 이상의 요소들은 찾지 않는다).


2. Example

#1버튼을 클릭하면 <ol>태그 한 단계 아래에 있는 <li>태그들을 찾아서 밑줄을 넣는다. 버튼을 클릭할 때마다 해당 스타일이 토글된다.


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


[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/child</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>
			</ol>
		</div>

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

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

<script>
const btnExecute = $("[name='btn-execute']");
const li = $("ol[name='bigtech'] > li");

btnExecute.click(function() {
	if(!li.is("[style]")) {
		li.css("text-decoration", "3px underline hotpink");
	} else {
		li.removeAttr("style");
	}
});

// ------------------------------------------------------
// 소스출력
// ------------------------------------------------------
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]child.html
0.00MB


5. Reference

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