JavaScript/jQuery

【jQuery/Selector #29】Has Attribute Selector [name]

1Q74 2023. 3. 4. 17:38

1. Description

jQuery("[attribute]") : (속성값이 없더라도)attribute속성이 설정되어 있는 Element를 찾는다.


 

2. Example

#1버튼을 클릭하면 <table>의 <td>에 name속성이 설정되어 있는 Element를 찾아서 배경색을 변경한다. 버튼을 클릭할 때마다 해당 스타일이 토글된다.


[1q74.tistory.com] javascript/jquery/selector/gt
Google Amazon Facebook
Tesla Twitter Netflex
My Big Company My Great Company My Awesom 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/gt</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 name="bigtech" border="1">
				<tr>
					<td>Google</td>
					<td name>Amazon</td>
					<td>Facebook</td>
				</tr>
				<tr>
					<td>Tesla</td>
					<td>Twitter</td>
					<td>Netflex</td>
				</tr>
				<tr>
					<td>My Big Company</td>
					<td name="mygreatcompany">My Great Company</td>
					<td>My Awesom Company</td>
				</tr>
			</table>
		</div>

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

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

<script>
var exampleContainer = $("[name='_1q74-example-1']");
	var nameElements = exampleContainer.find("> table td[name]");
var btnFind = $("[name='btn-find']");

btnFind.click(function() {
	if(!nameElements.is("[style]")) {
		nameElements.css("background", "deeppink");
	} else {
		nameElements.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-root"] {
	min-height: 150px;
}

[name="_1q74-example-1"] {
	min-height: 80px;
}

[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]name.html
0.00MB


5. Reference

https://api.jquery.com/has-attribute-selector/