본문 바로가기

WEB_TECH/jquery

[jQuery] 3. jQuery 셀렉터

jQuery 셀렉터는 HTML 엘리먼트를 그룹또는 단독으로 다룰수 있게 만듭니다.

이것을 잘 다룰줄 알아야 다음 것을 할 수 있습니다.

열심히 몸에 배도록 합시다.


 

jQuery 셀렉터


우리는 이전 글에서 HTML 엘리먼트를 선택하는 몇가지 예를 살펴 보았었죠.

그것은 jQuery로 개발자가 원하는 엘리먼트를 정확히 선택하는 키포인트입니다.

jQuery 셀렉터는 엘리먼트명, 속성명, 또는 다른 방법으로 그룹 또는 

단독 HTML엘리먼트들을 선택할 수 있게 해 줍니다.


[참고] HTML DOM에 이런 내용이 있습니다.

"Selectors는 DOM엘리먼트를 그룹 또는 싱글노드로 다룰수 있도록 합니다. "



jQuery 엘리먼트 셀렉터

jQuery 엘리먼트 셀렉터는 태그이름을 기반으로 엘리먼트를 선택하는 선택자입니다.

만일 이렇게 표현했다고 하면 

$("p") 

이것은 모든<p>엘리먼트들을 선택합니다.


[예제]

<!DOCTYPE html>

<html>

<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">

</script>

<script>

$(document).ready(function(){

  $("button").click(function(){

    $("p").hide();

  });

});

</script>

</head>


<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

<button>Click me</button>

</body>

</html>




jQuery #id 셀렉터

이렇게 $("#test")라고 사용하면 id가 테스트인 유일한 엘리먼트를 선택하게 됩니다.


[예제]

<!DOCTYPE html>

<html>

<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">

</script>

<script>

$(document).ready(function(){

  $("button").click(function(){

    $("#test").hide();

  });

});

</script>

</head>


<body>

<h2>This is a heading</h2>

<p>This is a paragraph.</p>

<p id="test">This is another paragraph.</p>

<button>Click me</button>

</body>


</html>



jQuery .class 셀렉터

jQuery 클래스선택자는 특정 클래스들의 요소들을 찾는데 사용됩니다.

$(".test") 라고 쓰면  class="test"인 모든 요소들을 선택하게 됩니다.

또한 $("p.intro")라고 하면 모든<p> 엘리먼트 내에 class="intro"인 요소들을 선택합니다.


[예제]

<!DOCTYPE html>

<html>

<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">

</script>

<script>

$(document).ready(function(){

  $("button").click(function(){

    $(".test").hide();

  });

});

</script>

</head>

<body>


<h2 class="test">This is a heading</h2>

<p class="test">This is a paragraph.</p>

<p>This is another paragraph.</p>

<button>Click me</button>

</body>

</html>


 


그밖의 다른 예


Syntax Description
$("*") 모든 요소 선택
$(this) current요소 선택
$("p.intro") class="intro"인 모든<p>요소 선택
$("p:first") 첫번째 <p>요소선택
$("ul li:first") 첫번째 <ul>요소의 첫번째 <li> 요소선택
$("ul li:first-child") 모든 <ul>요소의 첫번째 <li> 요소선택
$("[href]") href 속성이 있는모든 엘리먼트 선택
$("a[target='_blank']") 타겟속성값이 "_blank"인 모든<a> 요소를 선택
$("a[target!='_blank']") 타겟속성값이 "_blank"이 아닌 모든<a> 요소를 선택
$(":button") 모든 <button> 요소와 <input> 요소의 타입이="button" 인 요소 선택
$("tr:even") 모든 짝수 <tr> 요소 선택
$("tr:odd") 모든 홀수 <tr> 요소 선택



'WEB_TECH > jquery' 카테고리의 다른 글

[jQuery] 8. HTML Set  (0) 2013.04.22
[jQuery] 7. HTML Get  (0) 2013.04.22
[jQuery] 6. jQuery method chaining  (0) 2013.04.22
[jQuery] 5. jQuery 이펙트  (0) 2013.04.22
[jQuery] 4. jQuery이벤트  (0) 2013.04.22
[jQuery] 2. jQuery 문법  (0) 2013.04.11
[jQuery] 1. jQuery 시작하기  (0) 2013.04.11