Selector

DOM의 요소( element )를 선택.

 

DOM(Document Object Model)

- HTML 문서의 요소를 제어하기 위해 웹 브라우저에서 처음 지원

- DOM은 동적으로 문서의 내용, 구조, 스타일에 접근하고 변경하기 위한 방법

- 브라우저별로 DOM 구현이 호환되지 않음에 따라, W3C에서 DOM 표준 규격을 작성

 

기본 셀렉터

#id : 지정된 아이디를 가지는 엘리먼트와 일치하는 셀렉터.

element : 모든 <element> 엘리먼트와 일치하는 셀럭터(태그 등)

.class : 지정된 클래스명을 가지는 요소를 선택.

* : 모든 엘리먼트를 선택한다.

 

예제

더보기
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<style type="text/css">
* {
	padding: 0; margin: 0; box-sizing: border-box;
}
body {
	font-style: 14px;
	font-family: 맑은 고딕, 나눔고딕, 돋움, sans-serif;
}
a {
	color: #000; text-decoration: none;
}
a:hover, a:acrive {
	color: tomato; text-decoration: underline;
}
h3 {
	margin: 10px;
}

span, label {
	display: block;
}
.box {
	width: 350px; min-height: 50px; margin: 20px auto; padding: 15px;
	border: 3px dotted gray; 
}
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">

// 실행 안됨. DOM이 준비 되지 않았으므로
// $("p").css("border", "1px solid #777");
	
// DOM이 로딩 되었을 때 실행
$(function() {
	// 모든 요소
	$("*").css({color:"#333", "font-size":"13px"}); 
	// {}는 자바스크립트에서 객체
	
	// 태그 선택자
	$("p").css("border","2px dashed #333");
	
	// id 선택자
	$("#layout1").css({width:'300px', padding:'10px', border:'2px solid green'});
	
	// class 선택자
	$(".red").css("color", "red");
	
	// AND
	$("label.underline").css("text-decoration", "underline");
	
	// 바로 아래 자식 하나
	$("div > label").css("color", "tomato");
	
	// 모든 자식(손자도 포함)
	$("div label").css("background", "#ff0");
	
	// 인접 형제. 바로 다음 형제 하나
	$("label + span").css("border", "1px dashed red")
	
	// 다음에 나오는 일반 형제
	$("label ~ span").attr("title", "과목");
	
});

</script>

</head>
<body>

<h3> selector</h3>

<div class="box">
	<div id="layout1">
		<label>프로그래밍</label>
		<span class="red">자바</span>
		<span>C언어</span>
		<span class="underline">코틀린</span>
		<p>
			<label class="red underline">데이터베이스</label>
			<span>오라클</span>
			<span>MySQL</span>
			<span>빅데이터</span>
		</p>
	</div>
	<div id="layout2">
		<label>웹</label>
		<span>HTML</span>
		<span>CSS</span>
		<span>JavaScript</span>
		<p>
			<label>웹프로그래밍</label>
			<span>JSP</span>
			<span>PHP</span>
			<span>ASP.NET</span>
		</p>
		<p>
			<span>React</span>
			<label>기타</label>
			<span>jQuery</span>
		</p>
	</div>
	
</div>
</body>
</html>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<style type="text/css">
* {
	padding: 0; margin: 0; box-sizing: border-box;
}
body {
	font-style: 14px;
	font-family: 맑은 고딕, 나눔고딕, 돋움, sans-serif;
}
a {
	color: #000; text-decoration: none;
}
a:hover, a:acrive {
	color: tomato; text-decoration: underline;
}
h3 {
	margin: 10px;
}

.box {
	width: 350px; min-height: 50px; margin: 20px auto; padding: 15px;
	border: 3px dotted gray; 
}

.box span, .box label {
	display: block;
}

</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">

// 실행 안됨. DOM이 준비 되지 않았으므로
// $("p").css("border", "1px solid #777");
	
// DOM이 로딩 되었을 때 실행
$(function() {
	// span 태그의 글자색을 tomato로
	$("span").css("color", "tomato");
	
	// span 태그와 label 태그의 글자에 밑줄
	$("span, label").css("text-decoration", "underline");
	
	// div1 아이디의 글자색을 blue
	$("#div1").css("color", "blue");
	
	// div2 아이디의 글자를 진하게
	$("#div2").css("font-weight", "700");
	
	// c1 클래스의 배경색을 yellow로
	$(".c1").css("background", "yellow");
	
	// input 요소 중 name=subject인 요소
	$("input[name=subject]").css("background", "#eee");
	
	// form의 input 요소 중 name 속성을 가진 요소
	$("form input[name]").css("border", "none");
	
	// form의 input 요소 중 type=text와 type=password인 요소
	$("form input[type=text], form input[type=password]").css("border-bottom", "1px solid blue");
	
	// form의 input 요소 중 name 속성 값이 'a'로 시작하는 요소
	$("form input[name^=a]").css("border-right", "3px solid red");
	
	// form의 input 요소 중 title 속성 값이 '버튼'으로 끝나는 요소
	$("form input[title$='버튼']").css("border-left", "3px solid black");
	
	// form의 input 요소 중 name 속성 값이 'x'가 포함된 요소
	$("form input[name*=x]").css("border-left", "3px solid black");
	
	// form의 input 요소 중 title 속성 값에 '내용'이라는 단어(띄어쓰기 구분)가 들어간 요소
	$("form input[title~='내용']").css("background", "yellow");
	
	
});

</script>

</head>
<body>

<h3> selector</h3>

<div class="box">
	<div id="div1">테스트 1</div>	
	<div id="div2" class="c1">테스트 2</div>
	<span>테스트 3</span>
	<span>테스트 4</span>
	<div id="div3" class="c1">테스트 5</div>
	<span class="c1">테스트 6</span>
	<span class="c2">테스트 7</span>
</div>
<hr>

<div class="box">
	<p> <input type="text" name="subject" title="과목 입력"> </p>
	<form>
		<p> <input type="text" name="subject" title="과목 입력"> </p>
		<p> <input type="text" name="ax1" title="1장 제목 입력"> </p>
		<p> <input type="text" name="as2" title="1장 내용 입력"> </p>
		<p> <input type="text" name="bs1" title="2장 제목 입력"> </p>
		<p> <input type="text" name="bx2" title="2장 내용 입력"> </p>
		<p> <input type="password" name="pwd" title="패스워드 입력"> </p>
		<p> <input type="file" name="selectFile"> </p>
		<p>
			<input type="button" value="입력완료" title="입력 버튼">
			<input type="reset" value="다시입력" title="리셋 버튼">
		</p>
	</form>
</div>

</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<style type="text/css">
*{
	padding: 0; margin: 0;
}

body {
    font-size:14px;
	font-family:"맑은 고딕", 나눔고딕, 돋움, sans-serif;
}

a {
	color: #000;
	text-decoration: none;
}
a:hover, a:active {
	color: tomato;
	text-decoration: underline;
}

h3 {
	margin: 10px;
}

.btn {
	color:#333;
	font-weight:500;
	border:1px solid #ccc;
	background-color:#fff;
	text-align:center;
	cursor:pointer;
	padding:3px 10px 5px;
	border-radius:4px;
	font-family:"Malgun Gothic", "맑은 고딕", NanumGothic, 나눔고딕, 돋움, sans-serif;
}
.btn:active, .btn:focus, .btn:hover {
	background-color:#e6e6e6;
	border-color: #adadad;
	color: #333;
}

textarea:focus, input:focus{
	outline: none;
}
.boxTF {
	border:1px solid #999;
	padding:3px 5px 5px;
	border-radius:4px;
	background-color:#fff;
	font-family:"Malgun Gothic", "맑은 고딕", NanumGothic, 나눔고딕, 돋움, sans-serif;
}

.box{
	box-sizing: border-box;
	width: 500px;
	min-height: 50px;
	margin: 20px auto;
	border: 3px dotted gray;
	padding: 15px; 
}
</style>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function() {
	$("form input + span").hide();
	$("form input[type=text]").css("border", "1px solid #aaa");
	
	// focus 이벤트. button 제외
	$("form input").not($(":button")).focus(function() {
		$(this).css("border", "1px solid #f28011");
		// 이벤트를 발생시킨 바로 다음 형제중 span 태그
		$(this).next("span").show();
	});
	
	// blur 이벤트. button 제외
	$("form input").not($(":button")).blur(function() {
		$(this).css("border", "1px solid #aaa");
		// 이벤트를 발생시킨 바로 다음 형제중 span 태그
		$(this).next("span").hide();
	});
});

</script>

</head>
<body>

<h3>selectors 예제</h3>

<div class="box">
<form>
	<p>
		<input type="text" name="id">
	    <span>아이디 입력.</span>
	    <span>5~10자 이내</span>
	</p>
	<p>
		<input type="text" name="name">
		<span>이름 입력.</span>
	</p>
	<p>
		<input type="text" name="age">
		<span>나이 입력.</span>
	</p>
	<p>
		<input type="text" name="birth">
		<span>생년월일 입력.</span>
	</p>
	<p style="padding: 5px;">
	<!-- 
		<button type="button" class="btn"> 등록하기 </button>
		<button type="button" class="btn"> 등록취소 </button>
	-->
		<input type="button" class="btn" value="등록하기">		
		<input type="button" class="btn" value="등록취소">		
	</p>
</form>
</div>

</body>
</html>

focus 이벤트에서 button을 제외

blur이벤트에서 button을 제외

 

이외 filter 가 여러가지 있음. 

 

선택된 요소 접근 메소드

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<style type="text/css">
*{
	padding: 0; margin: 0;
}

body {
    font-size:14px;
	font-family:"맑은 고딕", 나눔고딕, 돋움, sans-serif;
}

a {
	color: #000;
	text-decoration: none;
}
a:hover, a:active {
	color: tomato;
	text-decoration: underline;
}

.btn{
    color:#333;
    font-weight:500;
    border:1px solid #ccc;
    background-color:#fff;
    text-align:center;
    cursor:pointer;
    padding:3px 10px 5px;
    border-radius:4px;
}

ul {
	list-style: none;
}
li{
	padding: 0;
}

h3{
	margin: 30px;
}

.box{
	box-sizing: border-box;
	width: 350px;
	min-height: 50px;
	margin: 20px auto;
	border: 3px dotted gray;
	padding: 15px; 
}
</style>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(function() {
	$(".btnOk").click(function() {
		// var name = $(".std").html(); // html 소스 반환(innerHTML 속성)
		var name = $(".std").text(); // 텍스트만 반환
		
		// 속성값 가져오기
		var num = $(".std").attr("data-num");
		
		// document.getElementById("score").value = 90;
		$("#score").val(90); // value 속성에 값 설정
		
		// value 속성 값 가져오기
		var subject = $("#subject").val();
		var score = $("#score").val();
		
		var s = "<p>학번 : <b>" + num + "</b></p>";
		s +="<p>이름 : <b>" + name + "</b></p>";
		s +="<p>과목 : <b>" + subject + "</b></p>";
		s +="<p>점수 : <b>" + score + "</b></p>";
		
		// 텍스트 설정
		// $("#layout").text(s);
		
		// html 콘텐츠 설정
		$("#layout").html(s);
		
	});
	
})

/*
-- 선택된 요소 접근 
  .html() : 해당 요소의 HTML 콘텐츠를 반환하거나 설정한다.
  .text() : 해당 요소의 텍스트 콘텐츠를 반환하거나 설정한다.
  .val() : <form>요소의 값을 반환하거나 설정한다
  .attr() : 해당 요소의 명시된 속성의 속성값을 반환하거나 설정한다.
  .width() : 선택한 요소 중에서 첫 번째 요소의 너비를 픽셀 단위의 정수로 반환하거나 설정한다.
  .height() : 선택한 요소 중에서 첫 번째 요소의 높이를 픽셀 단위의 정수로 반환하거나 설정한다.
  .position() : 선택한 요소 중에서 첫 번째 요소에 대해 특정 위치에 존재하는 객체를 반환한다.(getter 메소드)

-- 메소드 체이닝(method chaining)
  여러 개의 메소드가 연속으로 호출되는 것
  예 : $("ul").find("li").eq(1).append("자바");
*/
</script>

</head>
<body>

<h3>선택된 요소 접근</h3>
<div style="margin: 20px;">
	<button type="button" class="btn btnOk"> 확인 </button>
</div>
<hr>

<div class="box">
	<p>
		<!-- data-* : 개발자에 의해 만들어진 속성 -->
	    <span class="std" data-num="1"><b>홍길동</b></span>
	</p>
	<p> <input type="text" id="subject" value="자바"> </p>
	<p> <input type="text" id="score"> </p>
</div>

<div class="box">
	<p>결과</p>
	<div id="layout"></div>
</div>

</body>
</html>

+ Recent posts