JavaScript/jQuery

【jQuery/Selector #14】Class Selector (“.class”)

1Q74 2023. 2. 22. 14:58

1. Description

해당하는 CSS 클래스를 가지고 있는 Element들을 찾는다.

$(".class1, .class2, .class3, ...)과 같이 여러 클래스로 찾을 수 있지만, 그 중 하나는 반드시 매칭되어야 한다.


2. Example

#1버튼을 클릭하면 .tesla, .google, .apple 클래스를 가지고 있는 Element를 찾아서 border색생과 같은 색상으로 배경색을 채운다. 버튼을 클릭할 때마다 해당 스타일이 토글된다.


[1q74.tistory.com] javascript/jquery/selector/class
  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/class</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<style>
.tesla {
	border: 1px dotted red;
}

.google {
	border: 1px solid blue;
}

.apple {
	border: 1px dashed gray;
}
</style>
</head>
<body>

	<div name="_1q74-example-root">
		<div name="_1q74-example-1">
			<ol name="bigtech">
				<li class="google">Google</li>
				<li>Amazon</li>
				<li>Facebook</li>
				<ol>
					<li class="tesla">Tesla</li>
					<li>Twitter</li>
					<li>Netflex</li>
				</ol>
				<li class="apple">Apple</li>
			</ol>
		</div>

		<div name="_1q74-example-bottom">
			<br/>
			<button name="btn-execute">#1. $(".tesla, .google, .apple")</button>
		</div>
	</div>

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

<script>
const btnExecute = $("[name='btn-execute']");
const compaines = $(".tesla, .google, .apple");

btnExecute.click(function() {
	compaines.each(function(index, el) {
		const borderColor = $(el).css("border-color");
		const isNotSetBackgroundColor = ($(el).css("background-color") === "rgba(0, 0, 0, 0)");

		if(isNotSetBackgroundColor) {
			$(el).css("background-color", borderColor);
		} else {
			$(el).css("background-color", "");
		}
	});
});

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


5. Reference

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