728x90
반응형

http://jquery.com/



목차

Core

Selector

  기본 셀렉터
  계층 셀렉터
  기본 필터 셀렉터
  자식 필터 셀렉터
  내용 필터 셀렉터
  속성 필터 셀렉터
  가시 필터 셀렉터
  폼 셀렉터

Traversing



 1.9 버전 변경사항

http://jquery.com/upgrade-guide/1.9/





Core

jQuery의 핵심으로 jQuery 오브젝트를 의미 한다.


● jQuery 사용

jQuery()


$()

$().css();  ==  jQuery().css();    //jQuery는 $로 대체 가능.

jQuery() 메소드는 다른 라이브러리(프로토타입 등) 에서 $() 메소드를 사용 할 경우 사용한다.(충돌이 날 경우)


● jQuery(selector, [context]) 

 : CSS 선택 장치를 받고, 매치한 엘리먼트 집합의 jQuery 오브젝트를 돌려준다.

jQuery(selector, [context]) 

jQuery(element) 

jQuery(elementArray) 

jQuery(jQuery object) 

jQuery()

1
2
3
4
5
6
7
8
9
10
11
// 첫번째 폼의 모든 radio 객체
$("input:radio", document.forms[0])
 
// 모든 radio 객체
$("input:radio")
 
// 특정 객체(id가 myid인 객체)
$("#myid")  -> document.getElementById("myid")
 
// 바탕화면의 배경색 변경
$(document.body).css("background", "#FFFF00");

 


● jQuery() 

 : html 문자열을 받아 DOM Element(을)를 작성해, 그것들을 포함한 jQuery 오브젝트를 돌려준다.

jQuery(html, [ownerDocument]) 

jQuery(html, props) 

 

1
2
// body에 <div><p>Hello</p></div> 태그를 추가
$("<div><p>Hello</p></div>").appendTo("body");

 

        

● $(callback)

 : $(document).ready(callback)의 단축형

$(callback);

- $(document).ready(callback)은 문서가 사용가능한 시점을 자동으로 인식하여 주어진 콜백 함수를 동작시킨다.

- 자바스크립트의 window.onload=function(){...}에 대응 된다.

- onload 이벤트보다 먼저 실행.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$(document).ready(function(){
      alert("A");
});
 
//위는 아래와 같다
$(function(){
      alert("A");
});
 
//두번 다 실행
$(function(){
      alert("A");
});
$(function(){
      alert("B");
});
 
//한번 만 실행(jquery는 모든 펑션이 실행되는 반면 자바스크립트는 마지막 함수만 실행됨)
window.onload = function(){
      alert("A");
}
window.onload = function(){
      alert("B");
}

 


● .each()

 : 매치 되어진 모든 원소에 대해 주어진 콜백 함수를 실행한다. 루프의 의미이다.

$(object).each(function([index, Element]){});

 

index는 선택한 jQuery 객체 배열의 순번을 의미한다.

1
2
3
4
5
6
7
8
9
10
11
12
$(function() {
    $(document.body).click(function () {
        $("div").each(function (index) {
            if (this.style.color != "blue") {
                $(this).css("color", "blue");
                //this.style.color = "blue";
            } else {
                this.style.color = "";
            }
        });
    });
});

 


each를 사용할 때 주의할 사항은 return으로 메서드를 빠져나갈 수 없다는 것이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<h3>jQuery TEST PAGE</h3>
<input type="text" value="first input"/>
<input type="text" value="second input"/>
 
<script type="text/javascript">
    function eachTest() {
        $('input').each(function(idx) {
            var thisValue = $(this).val();
            if (thisValue.indexOf('first') != -1) {
                return;
                // return true 혹은 return == continue
                // return false == break
            }
            alert($(this).val());
        });    
    }
     
    eachTest();
</script>

 

위에 작성된 대로라면 아무런 메세지도 뜨지 않고 eachTest() 메서드가 종료되어야 하지만 실제 동작은 그렇지 않다.

이는 .each()가 return 혹은 return true를 continue로 받아들이기 때문인데 원래 의도대로 break를 하고 싶다면 return false를 써야한다.


이에 따르면 .each()의 콜백함수 내에서의 return은 함수나 메서드의 종료를 의미하지 않는다. 아래 소스를 주석이 있을때와 없을 때를 비교해보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<h3>jQuery TEST PAGE</h3>
<input type="text" value="first input"/>
<input type="text" value="second input"/>
 
<script type="text/javascript">
    function eachTest() {
//      var methodExit = false;    
        $('input').each(function(idx) {
            var thisValue = $(this).val();
            if (thisValue.indexOf('first') != -1) {
//              methodExit = true;
                return false;
            }
            alert($(this).val());
        });
         
//      if (methodExit) {
//          return;
//      }
         
        alert('i\'m still alive..');
    }
     
    eachTest();
</script>

 


● jQuery.each()

 : 주어진 컬렉션의 길이만큼 구분을 반복한다. $(selector).each()와 다르다.

  http://www.websamo.com/bbs/board.php?bo_table=jquery_api&wr_id=209&sfl=wr_subject&stx=each&sop=and

$.each(collection, callBack([indexInArray, valueOfElement]) { });

 

1
2
3
4
5
6
7
8
9
// Array
$.each(['firstVal', 'seconVal'], function(idx, val) {
    alert(idx + ": " + val);
});
 
// Map
$.each({a: "aaa", b: "bbb"}, function(name, val) {
    alert(name + ": " + val);
});

 

jQuery.each()는 .each()와 마찬가지로 return true/return false가 각각 continue/break를 의미한다.


● size( )

 : 매치되어진 원소들의 갯수를 반환한다.

$(object).size();

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
  <script type="text/javascript" src="http://code.jquery.com/jquery.min.js" ></script>
  <script type="text/javascript">
 
  $(function(){
        $(document.body).click(function () {
               $(document.body).append($("<div>"));
               var n = $("div").size();
               $("span").text("There are " + n + " divs." + "Click to add more.");
         }).click(); // trigger the click to start
  });
 
  </script>
 
  <style>
  body { cursor:pointer; }
  div { width:50px; height:30px; margin:5px; float:left;
       background:blue; }
  span { color:red; }
  </style>
 
</head>
<body>
  <span></span>
  <div></div>
</body>
</html>

 


● length

 : 매치되어진 원소들의 갯수를 반환한다.

$(object).length;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<html>
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery.min.js" ></script>
  <script type="text/javascript">
 
  $(function(){
     $(document.body).click(function () {
           $(document.body).append($("<div>"));
           var n = $("div").length;
           $("span").text("There are " + n + " divs." + "Click to add more.");
      }).trigger('click'); // trigger the click to start
  });
 
  </script>
 
  <style>
  body { cursor:pointer; }
  div { width:50px; height:30px; margin:5px; float:left;
       background:green; }
  span { color:red; }
  </style>
 
</head>
<body>
  <span></span>
  <div></div>
</body>
</html>

 

 


● get( )

 : 매치되는 모든 문서 원소들을 배열로 반환한다.

 : Return Array<element>

$(object).get();

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<html>
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery.min.js" ></script>
  <script type="text/javascript">
 
  $(function(){
      function disp(divs) {
          var a = [];
          for (var i = 0; i < divs.length; i++) {
               a.push(divs[i].innerHTML);
          }
          $("span").text(a.join(" "));
      }
 
     disp( $("div").get().reverse() );
  });
 
  </script>
 
  <style>
  span { color:red; }
  </style>
 
</head>
<body>
  Reversed - <span></span>
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</body>
</html>

 


● get(index)

 : 매치되는 원소들 중 주어진 인덱스에 해당하는 하나의 원소만 반환한다.

 : Return javascript object

$(object).get(index);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery.min.js" ></script>
  <script type="text/javascript">
 
  $(function(){
     $("*", document.body).click(function (e) {
           e.stopPropagation();
           var domEl = $(this).get(0);
           $("span:first").text("Clicked on - " + domEl.tagName);
      });
  });
 
  </script>
 
  <style>
  span { color:red; }
  div { background:yellow; }
  </style>
 
</head>
<body>
  <span> </span>
  <p>In this paragraph is an <span>important</span> section</p>
  <div><input type="text" /></div>
</body>
</html>

 

 


● index(subject)

 : 매치되어진 원소들에 대해 주어진 객체와 동일한것을 검색하여, 존재하면 그 원소들중에 몇번째에 해당하는가 하는 인덱스 번호를 반환한다.  인덱스는 0부터 시작한다.

$(object).index(element);

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<script type="text/javascript"
    src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
 
  $(function(){
     $("div").click(function () {
           // this is the dom element clicked
           var index = $("div").index(this);
           $("span").text("That was div index #" + index);
      });
  });
  </script>
 
<style>
div {
    background: yellow;
    margin: 5px;
}
 
span {
    color: red;
}
</style>
 
</head>
<body>
    <span>Click a div!</span>
    <div>First div</div>
    <div>Second div</div>
    <div>Third div</div>
</body>

 


● jQuery.fn.extend(object)

 : 제이쿼리에 새로운 함수를 확장한다.(플러그인으로 만들어 사용한다.)

 : Return jQuery object

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<script type="text/javascript"
    src="http://code.jquery.com/jquery.min.js"></script>
<script>
    jQuery.fn.extend({
        check : function() {
            return this.each(function() {
                this.checked = true;
            });
        },
        uncheck : function() {
            return this.each(function() {
                this.checked = false;
            });
        }
    });
 
    $(function() {
        $("#button1").click(function() {
            $('input').check();
        });
 
        $("#button2").click(function() {
            $('input').uncheck();
        });
    });
</script>
<style>
div {
    background: yellow;
    margin: 5px;
}
 
span {
    color: red;
}
</style>
 
</head>
<body>
    <form>
        <input type="checkbox" name=""> <input type="checkbox" name="">
        <input type="checkbox" name=""> <input type="checkbox" name="">
        <input type="checkbox" name=""> <input type="checkbox" name="">
    </form>
    <input type='button' id='button1' value='전체선택'>
    <input type='button' id='button2' value='전체해제'>
</body>

 



Selector

DOM의 요소(엘리먼트)를 선택


● DOM(Document Object Model) 이란?

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

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

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


● 기본 셀렉터 

http://api.jquery.com/category/selectors/basic-css-selectors/

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

1
2
// id가 myDiv인 객체의 스타일 변경
$("#myDiv").css("border","3px solid red");

 


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

1
2
3
// 모든 div 태그의 스타일 변경
$("div").css("border","3px solid red");
$("div").css({"backgroundColor": "yellow", "font-size": "9pt"});

 


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

1
2
// class 속성이 myClass인 객체의 스타일 변경
$(".myClass").css("border","3px solid red");

 


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

1
2
// 모든 엘리먼트의 스타일 변경
$("*").css("font-size","10pt");

 


selector1, selector2, ... selectorN : 각각의 지정된 셀렉터와 일치하는 엘리먼트 선택

1
2
3
4
5
// div, span, p 태그중 class 속성이 myClass인 스타일 변경
$("div, span, p.myClass").css("border","3px solid red");
 
//span태그와 p태그에 적용
$("span, p").css("color", "#000000");

 

 


● 계층 셀렉터

http://api.jquery.com/category/selectors/hierarchy-selectors/

ancestor descendant

 : 조상 <ancestor> 엘리먼트의 자손(descendant)인 모든<descentant> 엘리먼트를 선택

 : 기준이 되는 조상요소는 선택하지 않는다.

1
2
// ancestor descendant -> form 태그 안의 input 태그 스타일 변경
$("form input").css("border", "2px dotted blue");

 


parent > child

 : <parent>의 바로 아래 자식인 모든 <child> 엘리먼트를 선택(div 태그 안의 자식 div 태그등을 선택 할 경우)

1
2
3
4
5
6
7
8
9
// parent > child : 아이디가 main인 객체 아래의 일단계의 모든 객체 스타일 변경
$("#main > *").css("border", "3px double red");
$("div > div").css("border", "2px solid #000000");
 
<div>부모
    <div>안쪽DIV<br/>
        <div>안안쪽div</div>
    </div>
</div>

 


prev + next

 : <prev> 엘리먼트 바로 다음의 형재인 <next> 엘리먼트를 선택

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//prev + next :
//  label 바로 아래 태그가 input인 모든 input 태그의 스타일 변경 및 value 값을 설정
$("label + input").css("color", "blue").val("테스트 !!!")
            :
<label>Name:</label>
<input name="name" />
<label>Email:</label>
<input name="email" />
<input name="none" />   <!-- 변화 없음 --!>
  
$("label + input").css("background", "red");
/* 만약
<label> <input>
<label> <input>
<label> <input>
이런식으로 존재한다면 label 다음에 오는 모든 input이 선택되므로 결국 모든 input태그에 적용된다.
*/

 


prev ~ sibling

 : <prev> 엘리먼트 다음의 형제인 모든 <sibling> 엘리먼트를 선택

1
2
3
4
5
6
7
8
9
10
11
12
// prev ~ sibling -> 아이디가 prev인 객체의 형제인 모든 div 태그의 스타일 변경
$("#prev ~ div").css("border", "3px groove blue");
      :
<div>div 1</div>  <!-- 변화 없음 --!>
<div id="prev">div 2</div>   <!-- 변화 없음 --!>
<div>div 3</div>
<div>div 4<div id="small">div 4-1</div></div>   <!-- 4-1은 변화 없음 --!>
<span>span</span> <!-- 변화 없음 --!>
<div>div 5</div>
 
$("#div2 ~ div").css("color", "blue");
//형제(같은 레벨)에 적용, 여기서 적시한 아이디(div2)는 제외한다

 


● 기본 필터 셀렉터  

http://api.jquery.com/category/selectors/basic-filter-selectors/

:first : 페이지 처음 선택된 엘리먼트 선택

1
2
// 첫번째 tr 태그 스타일 변경
$("tr:first").css("font-style", "italic");

 


:last : 페이지 마지막 선택된 엘리먼트 선택

1
2
// 마지막 tr 태그 스타일 변경
$("tr:last").css({"backgroundColor": "yellow", "fontWeight": "bolder"});

 


:not(selector) : 주어진 셀렉터와 반대되는 모든 엘리먼트 선택

1
2
3
4
5
6
7
// checkbox 객체가 선택되지 않은 형재 태그인 span 태그의 스타일 변경
$("input:not(:checked) + span").css("background-color", "yellow");
         :
<input type="checkbox" name="a" />
<span>홍길동</span>
<input type="checkbox" name="b" checked="checked" />
<span>이순신</span>    <!-- 변화 없음 --!>

 


:even : 페이지의 짝수 번째 엘리먼트 선택(인덱스는 0부터 시작) 

1
2
// 짝수행의 스타일 변경(인덱스는 0부터 시작)
$("tr:even").css("background-color", "#bbbbff");

 


:odd : 페이지의 홀수 번째 엘리먼트 선택(인덱스는 0부터 시작) 

1
2
// 홀수행의 스타일 변경(인덱스는 0부터 시작)
$("tr:odd").css("background-color", "#bbbbff");

 


:eq(index) : 지정된 index 번째의 엘리먼트 선택

1
2
$("td:eq(2)").css("text-decoration", "blink");
// 2번째 인덱스의 td 태그의 스타일 변경(인덱스는 0부터 시작) - 하나의 td만 변경

 


:gt(index) : 지정된 index 번째의 엘리먼트(포함되지 않음) 이후의 엘리먼트 선택

1
2
// 인덱스가 4보다 큰 td 태그 스타일 변경
$("td:gt(4)").css("text-decoration", "line-through");

 


:lt(index) : 지정된 index 번째의 엘리먼트(포함되지 않음) 이전의 엘리먼트 선택

1
2
// 인덱스가 4보다 작은 td 태그 스타일 변경
$("td:lt(4)").css("color", "red");

 


:header : 헤더 <h1> ~ <h6> 엘리먼트 선택

1
2
// h1, h2, h3과 같은 헤더 태그 스타일 변경
$(":header").css({ background:'#CCC', color:'blue' });

 


:animated : 현재 애니메이션이 적용되고 있는 엘리먼트 선택

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 애니메이션이 동작하고 있는 것만 스타일 변경
          :
    <script type="text/javascript" src="jquery-1.7.2.min.js" ></script>
    <script type="text/javascript">
      $(document).ready(function(){
         $("#run").click(function(){
            $("div:animated").toggleClass("colored");
          });
          function animateIt() {
            $("#mover").slideToggle("slow", animateIt);
          }
          animateIt();
      });
   </script>
  <style>
     div {background:yellow; border:1px solid #AAA; width:80px; height:80px; margin:5px; float:left;}
     div.colored {background:green;}
  </style>
        :
  <button id="run">Run</button>
  <div></div>
  <div id="mover"></div>
  <div></div>

 


:focus : 현재 포커스가 있는 요소를 선택


:lang : 명시한 언어 코드에 해당되는 요소를 선택한다.

1
$("div:lang(en-us)").addClass("usa");

 


:target : 문서가 갖는 fragment identifier(단편 식별자?)를 ID로 갖는 요소를 선택한다.

예를 들어 http://example.com/#foo 에서 $("p:target") 이 셀렉터는 <p id="foo">를 선택할 것이다.


:root : root태그를 선택한다. HTML문서에서 :root는 항상 <html>요소를 리턴한다.


● 자식 필터 셀렉터 

http://api.jquery.com/category/selectors/child-filter-selectors/

:nth-child(index/even/odd/equation) : N/짝수/홀수/수식에 따른 번째 자식 엘리먼트 선택 

1
2
// tr의 2번째 자식의 td 태그 스타일 변경(인덱스는 1부터 시작) - 2번째 자식 열 전체
$("td:nth-child(2)").css("text-decoration", "blink");

 


:first-child : 첫 번째 자식 엘리먼트 선택

1
2
3
4
5
6
7
8
9
10
11
12
$("div span:first-child").css("text-decoration", "underline")
 
<div>
 <span>John,</span> <-- 적용
 <span>Karl,</span>
 <span>Brandon</span>
</div>
<div>
 <span>Glen,</span> <-- 적용
 <span>Tane,</span>
 <span>Ralph</span>
</div>

 


:last-child : 마지막 자식 엘리먼트 선택

1
2
3
4
5
6
7
8
9
10
11
12
$("div span:last-child").css("text-decoration", "underline")
 
<div>
 <span>John,</span>
 <span>Karl,</span>
 <span>Brandon</span> <-- 적용
</div>
<div>
 <span>Glen,</span>
 <span>Tane,</span>
 <span>Ralph</span> <-- 적용
</div>

 


:only-child : 동기(형제)가 없는 자식 엘리먼트 선택

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$("div button:only-child").text("Alone").css("border", "2px blue solid");
 
  <div>
  <button>Sibling!</button>
  <button>Sibling!</button>
 </div>
 <div>
  <button>Sibling!</button> <-- 적용
 </div>
 <div>
  None
 </div>
 <div>
  <button>Sibling!</button>
  <button>Sibling!</button>
  <button>Sibling!</button>
 </div>
 <div>
  <button>Sibling!</button> <-- 적용
 </div>
  

 


:first-of-type

:last-of-type

:nth-last-child(index/even/odd/equation)

:nth-last-of-type(index/even/odd/equation)

:nth-of-type(index/even/odd/equation)

:only-of-type


● 내용 필터 셀렉터 

http://api.jquery.com/category/selectors/content-filter-selector/

:contains(text) : 지정된 text 내용을 포함하는 엘리먼트 선택. 메서드 체인으로 사용하려면 filter()와 같이 써야한다. [각주:1]

1
2
3
4
5
// b 태그 안의 text에 j가 포함된 text의 스타일 변경
$("b:contains('j')").css("background", "yellow");
 
// order_no 클래스인 모든 요소 중 body값으로 20140121를 갖는 요소의 갯수
$('.order_no').filter(':contains("20140121")').size();

 


:empty : 자식을 가지지 않은 엘리먼트 선택

1
2
// 내용이 없는 td 태그에 text를 추가하고 스타일 변경
$("td:empty").text("테스트 !!!").css('background', 'rgb(255,220,200)');

 


:has(selector) : 지정된 selector와 일치하는 엘리먼트를 포함하는 엘리먼트 선택

1
2
// div 태그 안의 p 태그에 class 속성에 test 클래스 설정
$("div:has(p)").addClass("test");

 


:parent : 빈 엘리먼트를 제외하고, 텍스트도 포함해서 자식 엘리먼트를 가지는 엘리먼트 선택

1
2
3
// td 태그에 값이 존재하는 경우 애니메이션효과 부여
  (주어진 것이 부모인 것을 모두 받아온다. 비어있는 것은 포함 안함)
$("td:parent").fadeTo(1500, 0.3);

 

 


● 속성 필터 셀렉터 

http://api.jquery.com/category/selectors/attribute-selectors/

[attribute] : 지정된 속성(attribute)를 가지는 엘리먼트 선택

1
2
$("input[name]").css("background", "yellow"); 
// name이란 속성을 갖는 input 요소를 모두 선택한다.

 


 

[attribute|=value] : 속성값의 앞부터 단어로 검색(여기서 단어란 하이픈(-, hyphen)을 기준으로 한다.

1
2
3
4
5
6
7
<div id="en">div1</div>   <!-- 선택 -->
<div id="en-kr">div2</div>   <!-- 선택 -->
<div id="enkr">div3</div>   <!-- 선택되지 않는다 -->
  
<script type="text/javascript">
alert($("div[id|='en']").text());
</script>

 


[attribute=value] : 지정된 속성(attribute)과 값(valu)을 가지는 엘리먼트 선택

1
2
3
4
5
6
7
8
9
// input 객체의 name 속성이 test인 모든 input 객체 다음 객체의 text를 변경
$("input[name='test']").next().text("테스트 !!!");
      :
<input type="radio" name="test" value="1" />
<span>name?</span>
<input type="radio" name="test" value="2" />
<span>name?</span>
<input type="checkbox" name="ch" value="3" />
<span>man?</span>

 


[attribute!=value] : 지정된 속성과 같지않거나 지정된 속성 값을 가지지않는 엘리먼트 선택

1
2
3
4
5
6
7
8
9
// input 객체의 name 속성이 test가 아닌 모든 input 객체 다음 객체의 text를 변경
$("input[name!='test']").next().text("남자 ?");
      :
<input type="radio" name="test" value="1" />
<span>name?</span>
<input type="radio" name="test" value="2" />
<span>name?</span>
<input type="checkbox" name="ch" value="3" />
<span>man?</span>

 


[attribute^=value] : 지정한 값으로 시작하는  속성을 가진 엘리먼트 선택

1
2
// input 객체의 name 속성이 news로 시작하는 객체의 value 속성 값 설정
$("input[name^='news']").val("abc !");

 


[attribute$=value] : 지정한 값으로 끝나는  속성을 가진 엘리먼트 선택

1
2
// input 객체의 name 속성이 letter로 끝나는 객체의 value 속성 값 설정
$("input[name$='letter']").val("a letter");

 


[attribute*=value] : 지정한 값을 포함하는  속성을 가진 모든 엘리먼트 선택

1
2
// input 객체의 name 속성이 man을 포함하는 모든 객체의 value 속성 값 설정
$("input[name*='man']").val("man !!!");

 


[attribute~=value] : 지정한 값이 단어의 형태(공백으로 구분) 로 포함하는 엘리먼트 선택

1
2
3
4
5
<input name="man-news" />
<input name="milk man" />  <!-- 선택됨 -->
<input name="letterman2" />
<input name="newmilk" />
<script>$('input[name~="man"]').val('man 이 단어로 포함되어 있음');</script>

 


[attributeFilter1][attributeFilter2][attributeFilterN] : 지정한 속성 필터 셀럭터와 일치하는 모든 엘리먼트 선택

1
2
3
4
5
6
  <input id="man-news" name="man-news" />
 
  <input name="milkman" />
  <input id="letterman" name="new-letterman" />
  <input name="newmilk" />
<script>$('input[id][name$="man"]').val('only this one');</script>

 


 

● 가시 필터 셀렉터 

http://api.jquery.com/category/selectors/visibility-filter-selectors/

:hidden : 감춰진(hidden) 엘리먼트 선택

:visible : 보이는(visible) 엘리먼트 선택

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');
 
 // hidden 속성인 div 태그를 보이게 함
 $("div:hidden").show(3000);
       :
 <div style="display:none;width:70px; height:40px; background:#ee77ff; margin:5px; float:left;">
테스트 !!!</div>
 
 // 보이는 div 태그를 클릭 할 경우 스타일 변경
 $("div:visible").click(function () {
     $(this).css("background", "yellow");
 });
 
 // hidden 속성인 경우 보이게 함
  if ($('#myDiv').is(':hidden') )
     $('#myDiv').show();

 


● 폼 셀렉터

http://api.jquery.com/category/selectors/form-selectors/

:button : 모든 button 요소들 및 button 타입의 input 요소 선택

:checkbox : checkbox 타입의 모든 input 요소 선택

:file : file 타입의 모든 input 요소 선택

:focus : 현재 포커스가 있는 요소 선택

:image : image 타입의 모든 input 요소 선택

:input : 모든 input, textarea, select, button 요소 선택

:password : password 타입의 모든 input 요소 선택

:radio : radio 타입의 모든 input 요소 선택

:reset : reset 타입의 모든 input 요소 선택

:submit : submit 타입의 모든 input 요소 선택

:text : text 타입의 모든 input 요소 선택

:hidden : hidden 타입의 모든 input 요소 선택

:enabled : 현재 enable 상태인 모든 요소 선택

:disabled : 현재 disable 상태인 모든 요소 선택

1
2
3
4
5
6
7
8
$(document).ready(function(){
 $("input:enabled").val("this is it");
});
 
<form>
 <input name="email" disabled="disabled" />
 <input name="id" />
</form>

 


:checked : 체크된 모든 요소 선택

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function countChecked() {
   var n = $("input:checked").length;
   $("div").text(n + (n == 1 ? " is" : " are") + " checked!");
 }
 countChecked();
 $(":checkbox").click(countChecked);
 
 
<form>
 <input type="checkbox" name="newsletter" checked="checked" value="Hourly" />
 <input type="checkbox" name="newsletter" value="Daily" />
 <input type="checkbox" name="newsletter" value="Weekly" />
 <input type="checkbox" name="newsletter" checked="checked" value="Monthly" />
 <input type="checkbox" name="newsletter" value="Yearly" />
</form>

 


:selected : 선택된 모든 요소 선택

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$("select").change(function () {
       var str = "";
       $("select option:selected").each(function () {
             str += $(this).text() + " ";
           });
       $("div").text(str);
     })
     .trigger('change');
 
 
<select name="garden" multiple="multiple">
 <option>Flowers</option>
 <option selected="selected">Shrubs</option>
 <option>Trees</option>
 <option selected="selected">Bushes</option>
 <option>Grass</option>
 <option>Dirt</option>
</select>

 


 

 



Traversing

DOM의 선택 조작


● Filtering

eq(index) : 인덱스를 지정해 요소 집합으로 부터 한개를 선택한다.(인덱스는 0부터 시작)

1
2
3
4
5
6
7
8
9
10
// 0,1,2 : 3번째 li element
$('li').eq(2).css('background-color', 'red');
 
// -1,-2 : 끝에서 2번째 li element
$('li').eq(-2).css('background-color', 'red');
 
$(document).ready(function () {
    alert($('p:eq(2)').text()); //셀렉터 필터
    alert($('p').eq(2).html()); //메서드
});

 


hasClass(class) : 요소 집합 가운데 한개라도 지정의 클래스를 가지는 요소가 있으면 true를 리턴


filter(expr)

 : 지정한 조건식에 매치한 요소만을 추출한다.

 : find(expr)와 흡사하지만 filter는 선택된 요소를 대상으로 하며 find는 선택된 요소 중 자손들만을 대상으로 한다.

1
2
3
4
5
6
$(function() {
       $('img').addClass('redBorder') // 모든 이미지에 redBorder 클래스 적용
       .filter('[title*=안드로이드]').addClass('five') //'안드로이드'로 시작하는 title속성을 가진 요소들 모두 five 클래스 적용
       .end() // 부모로 이동
       .filter('[alt$=디드]').removeClass('redBorder'); // '디드'로 끝나는 스타일 제거
});

 

※ filter chain 예제

1
$("input:radio[name='notice_typ']:checked");

 

위는 input 태그 중 radio타입이며 name속성의 값이 'notice_typ'인 것 중 체크된 상태인 엘리먼트를 가져오는 표현식이다.

이를 filter chain으로 작성하면 다음과 같다.

1
$("input").filter(":radio").filter('[name="notice_typ"]').filter(':checked').val();

 


filter(fn)

 : 지정된 함수와 매치되지 않는 요소들을 제거한다. 이 함수는 모든 요소에 대해서 $.each (와)과 같이 순서에 실행된다. 이 때에 false(을)를 돌려주면, 그 요소는 집합으로부터 없어지며 false 이외의 값을 돌려주면 그 요소는 남는다.

 : fn - 대상 element 중 원하는 element를 filter할 callback function


is(expr) : 요소 집합 가운데, 한개라도 값이 있으면 true(을)를 돌려준다.

1
2
3
4
5
6
7
8
$(document).ready(function() {
     //myForm 영역에 submit 버튼이 있는지 검사
     if ($('#myForm').children().is("input[type=submit]")) {
        alert("있다.");
     } else {
        alert("없다");
     }
});

 


map(callback) : jQuery오브젝트중의 요소 집합을 콜백 함수에 건네주어, 반환값을 배열로서 돌려준다.


not(selector)요소 집합으로부터 조건식에 합치한 요소를 삭제한다.

 : not()은 선택된 jQuery객체 배열에서 지정한 요소가 아닌것만 리턴한다. (즉, 지정한 요소를 제거한다.)

 : selector는 expression, jQuery객체 혹은 함수[각주:2]가 올 수 있다.

1
2
3
4
//라디오버튼을 제외한 input태그에 배경색을 yellow로 설정
$('input').not("input[type=radio]").each(function () {
    $(this).addClass("Yellow").css("border","1px solid red");
});

 

1
2
// div 태그 중 id가 target이 아닌것들의 갯수
$('div').not('#target').length; 

 


slice(start, [end]) : 지정한 범위에 있는 요소를 선택한다.


has( selector ) 혹은 has( contained ) 

 : has()는 jQuery의 DOM 선택자를 필터링하는 메소드로 부모 요소가 가진 특정한 자식 요소들을 확인하여 선택할 수 있다.

1
2
3
      jQuery('div').has('ul');
//문서의 모든 DIV 요소를 찾아내고 이 요소들 중
//UL 요소를 포함하는 DIV 요소만을 선택하여 반환하는 코드

 


● Finding

add(expr)

 : jQuery를 통해 선택된 element set에 add(expr)에 일치하는 element들을 추가한다. (단, add()에 의해 추가되는 element가 document에 추가되는 것은 아니며, 검색된 대상 집합에만 추가된다.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function() {
    var addElement = $("p").add("span");
    var leng = addElement.length;
    for(var i=0; i<leng; i++) {
     $("div").append($(addElement[i]).clone());
    }
    alert($("div").html());
});
 
 
<p>Hello</p>
<p>
    <span>Hello Again</span>
</p>
<div/>

 


children([expr])

 : 요소 집합이 가지는 아이 요소 중에서, 조건식에 맞는(생략시는 모두) 요소를 선택한다.

 한 단계 아래의 자식만 선택한다. 계층 셀렉터의 parent > child 와 같으며 오브젝트가 대상일 때 유용하다.


closest(expr)

 : 지정 요소로부터 가장 가까운 친요소를 선택한다.

 http://www.jquerykorea.pe.kr/closest

 http://api.jquery.com/closest/

 직계조상 중[각주:3] expr에 해당하는 가장 가까운 요소를 선택한다. 

 예를 들어 table과 tr이 class="parent" 일 때 td에서 가장 가까운 ".parent"는 tr이다.


contents()

 : 대상의 text node[각주:4]를 포함한 한 단계 아래의 자식요소를 선택한다.

 : iframe을 대상으로 contents()를 사용할 경우 해당 프레임의 document 객체를 리턴한다.


find(expr)

 : 요소 집합으로부터 조건식에 맞는 자손 요소를 추출한다. 

 : find는 선택된 객체를 제외한 자손 element중에서만 탐색한다.

1
2
3
4
5
//<div> 중 <p>의 css를 변경
$("div").find("p").css("color", "blue");
 
//<body>의 모든 자손요소를 리턴
$('body').find('*');

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<form>
    <div>
        <input type="radio" value="aa" name="rad"/>a
        <input type="radio" value="bb" name="rad"/>b
    </div>
    <input type="radio" value="cc" name="rad"/>c
    <input type="button" value="눌러" onclick="fn_test(this.form)"/>
</form>
//일때
 
$("input[type='radio']").find("[value='aa']").attr("disabled", true); //탐색불가
 
//단, 아래처럼 filter로 바꾸면 가능
$("input[type='radio']").filter("[value='aa']").attr("disabled", true);
 
//find의 경우엔 다음처럼 작성한다.
$("div").find("input[type='radio']").attr("disabled", true);
//div태그 자손 중 type이 radio인 요소를 모두 disable
 
//혹은
$("div").find("[value='aa']").attr("disabled", true);
//div 자손 중 value='aa'인 요소 disable

 

 


next([expr])

 : 대상이 되는 element를 기준으로 동일한 노드의 현재 위치 다음의 인접한 element를 찾는다. 입력 값(expr)이 생략된 경우 대상 element 바로 다음의 element를 리턴하며, 입력 값(expr)이 있을 경우 next(...)의 대상이 되는 element가 expr 표현식과 일치할 경우만 리턴한다.

1
2
3
4
5
6
7
8
9
10
11
12
    $("p").next().each(function(i) {
...
    });
 
<p>Hello</p>
<p>Stone</p> <-- 적용
<div>  <-- 적용
    <span>Very Hot</span>  <-- 적용
</div> <-- 적용
<div>Let's Start</div> <-- 선택하지 않는다
 
//next는 다음에 오는 1개의 element와 해당 element의 하위요소만 선택한다.

 

 


nextAll([expr])

 : 형제 요소 중 대상과 일치하는 모든 요소를 리턴한다. 검색값을 생략할 경우 모든 형제가 리턴된다.

1
2
3
4
5
6
7
8
9
10
11
12
    $("p").nextAll().each(function(i) {
...
    });
 
<p>Hello</p>
<p>Stone</p> <-- 적용
<div><-- 적용
   <span>Very Hot</span><-- 적용
</div> <-- 적용
<div>Let's Start</div> <-- 적용
 
//next()가 다음 요소 하나를 가져오는 반면 nextAll()은 모든 요소를 가져온다.

 


parent([expr]) : 각 요소의 부모 요소를 리턴한다.

1
alert($("p").parent().html());

 


parents([expr]) : 입력 값 (expr)에 해당하는 부모 노드 모두를 찾는다. (※ body와 html을 포함한다)

1
$("p").parents();

 


prev([expr])

 : 대상이 되는 요소를 기준으로 동일한 노드의 현재 위치 이전의 인접한 요소를 찾는다. 입력 값이 존재하지 않을 경우 바로 앞의 요소를 리턴한다.

1
$("p").prev();

 


prevAll([expr])

 : 대상이 되는 요소를 기준으로 현재 노드와 같고 현재 위치 이전의 모든 형제 요소를 찾는다. 입력 값이 존재하지 않을 경우 대상 요소 이전의 요소 중 모든 형제요소를 리턴한다.

1
$("p:last").prevAll();

 


siblings(expr)

 : 입력 값이 존재할 경우 입력 값에 해당하는 요소를 찾는다.

 : 대상이 되는 노드를 기준으로 같은 노드의 위치에 있는 (자신을 제외한)모든 노드를 찾는다. 

 : 선택자를 제외한 형제를 선택하는 용도로 사용할 때, 기준이 되는 객체가 둘 이상일 경우 자기 자신들도 선택하므로 주의할 것

1
2
3
$("div").siblings().each(function(i) {
      ...
});

 


nextUntil( [selector,] [filter] )

prevUntil( [selector,] [filter] )

parentsUntil( [selector,] [filter] )

 : jQuery 1.4에는 DOM을 탐색하기 위한 3개의 메소드가 추가되었다. 이것은 특정한 방향으로 DOM을 선택할 수 있음을 의미한다.

 : 다음에 오는 요소가 필터조건에 부합할 경우 탐색을 중단한다. 탐색 시작 시 현재 요소와 마지막 요소는 포함하지 않는다. (즉 자신과 지정한 요소)

 : 만약 필터에 걸리는 요소가 없을 경우 모든 형제요소를 리턴한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
<ul>
    <li>사과</li>
    <li>바나나</li>
    <li>포도</li>
 
    <li>딸기</li>
    <li>토마토</li>
    <li>오렌지</li>
</ul>
 
 
jQuery('ul li:contains(사과)').nextUntil(':contains(토마토)');
// Selects 바나나, 포도, 딸기

 


선택자에는 표현식 대신 DOM 노드 또는 jQuery 객체가 올 수 있다. 다음 예제는 위와 결과가 같다.

1
2
3
4
5
6
7
8
var foo;
 
$('li').each(function() {
    if ($(this).text() == '토마토')
      foo = $(this);
});
 
$('ul li:contains(사과)').nextUntil(foo); // select 바나나, 포도, 딸기

 

 


● Chaining

andSelf() : 현재의 요소에 가세하고, 하나전의 요소 집합을 선택한다. 결과 집합 element에 최초 대상이 되었던 element를 포함시켜서 리턴한다.

1
2
3
4
$("p").find("span").each(function(i) { ... });
$("p").find("span").andSelf().each(function(i) { ... });
//위 두 예제에서 첫번째 예제가 최초대상인 <p> element를 선택하지 않는 반면
//두번째 예제는 최초대상인 <p> element도 같이 선택하게 된다.

 

 


end() : 연쇄 참조시에, 현재의 선택으로부터 하나전 상태에 되돌린다.

1
2
alert($("p").html());
alert($("p").find("span").end().html());

 

 



  1. $.contains()는 용도가 다른 메서드다. (텍스트가 아닌 객체가 객체를 소유하는지 판단한다) [본문으로]
  2. not(function(index)) [본문으로]
  3. 조상의 형제는 제외한다. [본문으로]
  4. 혹은 textContent [본문으로]
728x90
반응형
블로그 이미지

nineDeveloper

안녕하세요 현직 개발자 입니다 ~ 빠르게 변화하는 세상에 뒤쳐지지 않도록 우리모두 열심히 공부합시다 ~! 개발공부는 넘나 재미있는 것~!

,