1. Description
jQuery(":only-child") :부모의 하위 Element들 중에서 오직 하나의 자식 Element를 가지고 있는 Element에 매칭된다. |
즉, 다른 형제 Element가 있다면 매칭되지 않는다. |
2. Example
#1버튼을 클릭하면 <td>태그가 하나인 Element를 찾아서 배경색을 변경한다. 버튼을 클릭할 때마다 스타일이 토글된다.
child#1-1 | |||
child#2-1 | |||
child#3-1 | child#3-2 | child#3-3 | child#3-4 |
[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/only-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">
<table border="1">
<tr>
<td colspan="4">child#1-1</td>
</tr>
<tr>
<td colspan="4">child#2-1</td>
</tr>
<tr>
<td>child#3-1</td>
<td>child#3-2</td>
<td>child#3-3</td>
<td>child#3-4</td>
</tr>
</table>
</div>
<div name="_1q74-example-bottom">
<br/>
<button name="btn-find">#1. $("[name='_1q74-example-1'] td:only-child")</button>
</div>
</div>
<hr/>
<h5>[HTML Code]</h5>
<div name="_1q74-source">
</div>
<h5>[//HTML Code]</h5>
<script>
var btnContainer = $("[name='_1q74-example-bottom']");
var btnFind = btnContainer.find("[name='btn-find']");
var elements = $("[name='_1q74-example-1'] td:only-child");
btnFind.click(function() {
if(!elements.is("[style]")) {
elements.css("background", "#2C10D8");
} else {
elements.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", " "));
</script>
<style>
[name="_1q74-example-root"] {
min-height: 170px;
}
[name="_1q74-example-1"] {
min-height: 140px;
}
[name="_1q74-example-root"] [type="image"]{
width: 100px;
}
[name="_1q74-example-1"] td {
min-width: 100px;
min-height: 30px;
}
[name|="_1q74-example"] button
,[name="_1q74-source"] button {
background: lightgray;
border: 5px outset;
min-height: 35px;
}
[name|="_1q74-example"] button:active
,[name="_1q74-source"] button:active {
border: 2px inset;
min-height: 35px;
}
</style>
</body>
</html>
4. File
5. See also
6. Reference
https://api.jquery.com/only-child-selector/
'JavaScript > jQuery' 카테고리의 다른 글
【jQuery/Selector #53】:parent Selector (0) | 2023.03.15 |
---|---|
【jQuery/Selector #52】:only-of-type Selector (0) | 2023.03.15 |
【jQuery/Selector #50】:odd Selector (0) | 2023.03.15 |
【jQuery/Selector #49】:nth-of-type() Selector (0) | 2023.03.14 |
【jQuery/Selector #48】:nth-last-of-type() Selector (0) | 2023.03.14 |