🌇

2. jQuery의 필터와 실행방법


Index

Index
 

2. jQuery의 필터와 실행방법

2.1 jQuery 필터

다음 약어들은 미리 알아두시면 이해하기 좋습니다. 뒤에 언급된 것이 표준입니다. 외우기에는 litter이나 greater가 더 쉽기 때문에 함께 명시해둡니다. jQuery에서 없는 것은 없다고 표시를 해두었습니다. 다른 언어에서 보시게 될 수도 있어서 함께 명시해둡니다.
  • eq - equal ( = )
  • ne - not equal ( <> )
  • (없음) le - little or equal ( <= ), less-than or equals sign
  • (없음) ge - greater or equal ( >= ), greater-than or equals sign

기본 필터

index는 음수도 허락합니다.
  • :eq(index) $("li").eq(3).css("color", "red" );
  • :even(짝수, 2븐 == 짝수)
  • :odd(홀수, odd는 3글자 홀수)
  • :first
  • :last
  • :gt(index) - 큰 숫자 선택 $("li:gt(2)").css( "backgroundColor", "yellow");
  • :lt(index) - 작은 숫자 선택 $("li:lt(2)").css( "backgroundColor", "yellow");
  • :not(filter) - $("input:not(:checked)+span").css( "background-color", "yellow" );

차일드 필터

  • :first-child, :last-child
  • :nth-child(2)
  • :nth-child(even), :nth-child(odd)
  • :nth-child(3n)
<!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jquery</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <ul> <li>hello world</li> <li>hello world</li> <li>hello world</li> <li>hello world</li> <li>hello world</li> <li>hello world</li> <li>hello world</li> <li>hello world</li> <li>hello world</li> <li>hello world</li> </ul> <script> // $("li").eq(3).css("color", "red" ); // $("li:gt(6)").css("color", "red"); // $("li:nth-child(2n)").css("color", "red"); // $("li:nth-child(3n)").css("color", "red"); // $("li:first").css("color", "red"); // $("li:last").css("color", "red"); // $("li:even").css("color", "red"); $("li:odd").css("color", "red"); </script> </body> </html>

속성 필터

  • :attributeContains - input[name*='man’]
    • <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>attributeContains demo</title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body> <input name="man-news"> <input name="milkman"> <input name="letterman2"> <input name="newmilk"> <script> $("input[name*='man']").val("has man in it!"); </script> </body> </html>
      공식문서 예제
  • :attributeEquals - input[name='newsletter’]
    • <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>attributeEquals demo</title> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body> <div> <label> <input type="radio" name="newsletter" value="Hot Fuzz"> <span>name?</span> </label> </div> <div> <label> <input type="radio" name="newsletter" value="Cold Fusion"> <span>value?</span> </label> </div> <div> <label> <input type="radio" name="newsletter" value="Evil Plans"> <span>value?</span> </label> </div> <script> $("input[value='Hot Fuzz']").next().text("Hot Fuzz"); </script> </body> </html>
      공식문서 예제
 
 

컨텐츠 필터

  • :contains
    • <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>has demo</title> <style> .full { border: 1px solid red; } </style> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body> <p>hello hi</p> <p>hello !!</p> <p>hello world</p> <p>hello</p> <p>hello world</p> <script> $("p:contains(world)").css("color", "red"); </script> </body> </html>
  • :empty
    • <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>empty demo</title> <style> p { background: yellow; } </style> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body> <p> Hello, <span>Person</span> <em>and person</em>. </p> <button>Call empty() on above paragraph</button> <script> $( "button" ).click(function() { $( "p" ).empty(); }); </script> </body> </html>
      공식문서 예제
  • :has(selector)
    • <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>has demo</title> <style> .full { border: 1px solid red; } </style> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body> <ul> <li>Does the UL contain an LI?</li> </ul> <ul> hello world </ul> <script> $("ul").has("li").addClass("full"); </script> </body> </html>
      공식문서 예제
 

 

2.2 실행방법

 
  • 값 변경
  • DOM 탐색
  • DOM 편집
  • CSS
  • 이벤트
  • 효과
  • AJAX
  • 유틸리티
 
 
jQuery에서 값을 불러오는 방법은 다음과 같습니다.
 
  • 값 CODE
$(".one").val(); // 값 읽어오기 $(".two").val('hello'); // 값 쓰기
 
jQuery는 $(“”)의 부분에서 코드가 적용 될 부분을 작성합니다. 그리고 이 부분은 함수에 해당합니다. 예를 들어 아래와 같이 구현하고 실행시키면 콘솔창에 hello world가 찍힙니다.
function $(value){ console.log(value); } $('hello world');
 
다음과 같이 jQuery로 변수를 만들어 사용할 때에는 앞에 $ 표시를 하는 경우가 많습니다. 이는 뒤에 연결되는 메서드 체이닝이 jQuery로 가능하다는 것을 명시하기 위함입니다.
let $value = $('#one')
 
위에서처럼 속성 값을 불러왔다면 .hide(); 와 같이 실행했을 때 적용되는 코드를 넣습니다.
 
notion imagenotion image
 
선택 방법은 기본 선택과 계층 선택이 있습니다.
  • 기본 선택 : element, .class, #id, all(*)
  • 계층선택 : child(>)
선택자는 CSS처럼 사용할 수 있습니다. $("ul li"), $("#header .list-item"), $(".table-hover th") 처럼요.
 
이 파트에서는 jQuery에서 DOM을 탐색하는 방법에 대해 알아보도록 하겠습니다. DOM의 탐색은 일반적으로 선택자를 통해서 이루어집니다.
  • 탐색 CODE1
<div class="wrapper"> <h1 class="title">TITLE</h1> <ul class="items"> <li class="items">item 1</li> <li class="items">item 2</li> </ul> </div>
 
  • 탐색 CODE2
$("span").parent(); $("div").children(); $("div").first(); $("div").last();
 
빨간 네모 박스가 쳐진 곳이 선택자에 해당하는 부분입니다.
$("span").parent();는 부모 선택자입니다. 이것은 부모 인자로 잡히는 모든 상위 인자를 반환합니다. $("div").children();는 자식선택자로, 선택된 요소의 자식에 해당하는 것을 전부 반환합니다. $("div").first();는 선택한 요소 중 가장 첫번째를 반환합니다. 이 예시에서는 div 중 가장 처음 나오는 div를 반환합니다. 반대로 $("div").last();는 여러 개의 div 중 가장 마지막에 나오는 div를 반환합니다.
 
다음으로는 DOM의 편집에 대해 알아보도록 하겠습니다. 먼저 제이쿼리의 문자를 편집하는 메소드에 대해 알아보도록 하겠습니다.
 
  • 편집 CODE1
$("test1").text("Hello World!"); $("test2").html("<b>Hello World!</b>"); $("test3").val("<b>Hello World!</b>");
위 세 코드는 텍스트를 받아오거나 변경할 수 있게 합니다. 세 코드는 비슷해 보이지만 차이점이 존재합니다.
notion imagenotion image
 
  • 편집 CODE2
$("p").append("Some appended text."); $("p").prepend("Some prepended text."); $("#div1").remove();
append()는 객체를 선택한 객체(p)내의 가장 마지막 요소로 붙입니다. prepend()는 객체를 선택한 객체 내의 가장 첫번째 요소로 붙입니다. remove()는 선택한 객체를 삭제시킵니다.
DOM 편집은 html 요소 뿐만 아니라 css도 변경할 수 있습니다. 아래의 코드를 함께 공부해 보도록 하겠습니다.
  • sample code (사용할만한 코드로 추가해드립니다. 다 아실 필요는 없어요. 백과사전처럼 인터넷 찾아보시면서 하시면 됩니다.)
$('ul').append('<li>hello world end</li>'); $('ul').prepend('<li>hello world start</li>'); $('ul').after('<h2>끝!</h2>'); $('ul').before('<h2>시작!</h2>');
 
  • CSS 편집 CODE
$("div").addClass("important"); $("h1,h2,p").removeClass("blue"); $("h1,h2,p").toggleClass("blue"); $("p").css("background-color"); $("p").css("background-color","yellow");
먼저 addClass() 함수는 클래스를 추가하는 것이 가능합니다. 위 코드에서는 div에 important라는 클래스가 추가되게 됩니다. (카멜케이스(testTestTest)와 케밥(test-test-test)방식 모두 사용가능하지만 통일성을 위해 카멜케이스를 추천해드립니다. 케밥방식으로 했을 때 동작을 안하면 카멜로 바꿔보세요!)
 
예를 들어 위와 같은 코드에 $(“div”).addClass(“world”)라는 코드를 실행하면 다음과 같이 클래스가 변화하게 됩니다.
 
.addClass() 적용 전
 
<div class="hello">hello world!</div>
 
.addClass() 적용 후
 
<div class="hello world">hello world!</div>
 
notion imagenotion image
 
이제부터는, jQuery의 effect에 대해 알아보도록 하겠습니다. effct를 사용하면 마치 파워포인트의 애니메이션과 같이 요소에 다양한 효과를 줄 수 있습니다.
 
  • effect CODE
$("p").hide(); $("p").show(); $("p").toggle(); $("#div1").fadeIn(); $("#div1").fadeOut(); $("#div1").fadeToggle(); $("#div3").fadeIn(3000); // 모달창, 이미지 갤러리 등에서 사용
 
notion imagenotion image
 
 

 

연습문제

<!-- 1. items 부모를 찾아 background-color를 파란색으로 바꿔주세요. 2. items 2번째 color를 빨간색으로 바꿔주세요 3. ul2의 자식인 li요소를 선택하여 1번부터 3번까지 color를 녹색으로 바꿔주세요. 4. ul2의 자식인 li요소를 선택하여 7번부터 10번까지 color를 파란색, background-color를 빨간색으로 바꿔주세요. --> <div class="wrapper"> <h1 class="title">TITLE</h1> <ul> <li class="items">item 1</li> <li class="items">item 2</li> <li class="items">item 3</li> </ul> </div> <ul class="ul2"> <li>hello</li> <li>hello</li> <li>hello</li> <li>hello</li> <li>hello</li> <li>hello</li> <li>hello</li> <li>hello</li> <li>hello</li> <li>hello</li> </ul>
 
답안
$('.items').parent().css('backgroundColor', 'blue'); $('.items').eq(1).css('color', 'red'); $('.ul2').children('li:lt(3)').css('color', 'red'); $('.ul2').children('li:lt(3)').css('color', 'green'); // $('.ul2 li:lt(3)').css('color', 'green'); $('.ul2').children('li:gt(5)').css('color', 'red'); // $('.ul2 :nth-child(n+3)').css('color','green'); // $('.ul2 > li').slice(6,).css('color', 'red').css('backgroundColor', 'blue'); // $('.ul2 > li').slice(6,).css({ color: "blue", background: "red" })
 
 

추가 코드

.slice( start [, end ] )
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>has demo</title> <style> .full { border: 1px solid red; } </style> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body> <!-- div#${value-$}*10 --> <script> $('div').slice(2, 5).css('color', 'red'); </script> </body> </html>
.filter( selector )
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>has demo</title> <style> .full { border: 1px solid red; } </style> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body> <!-- div#${value-$}*10 --> <script> // $('div').filter(':even').css("color", "red"); $('div').filter((index, selector) => { if (index % 3 == 0) { console.log(selector) $(selector).css('color', 'red') } }); </script> </body> </html>
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>has demo</title> <style> div { width: 60px; height: 60px; margin: 5px; float: left; border: 2px white solid; } </style> <script src="https://code.jquery.com/jquery-3.5.0.js"></script> </head> <body> <div></div> <div class="middle"></div> <div class="middle"></div> <div class="middle"></div> <div class="middle"></div> <div class="middle"></div> <div class="middle"></div> <div></div> <script> $("div") .css("background", "#c8ebcc") .filter(".middle") .css("border-color", "red"); </script> </body> </html>
공식문서 예제