[jQuery] 기본 구문과 선택자

jQuery 의 기본 구문은 $(selector).action() 이다
HootJem's avatar
Sep 06, 2024
[jQuery] 기본 구문과 선택자
jQuery 의 기본 구문은 $(selector).action() 이다
  • $ : jQuery 를 정의 , 접근
  • () : HTML 요소 선택, 찾기
  • .action() : jQuery 작업
 
예시 : hide 는 숨기는 작업을 하는 명령어
  1. <p> 엘레먼트 숨기기
    1. $("p").hide();
  1. id=”test” 인 요소 숨기기
    1. $(”#test”).hide();
  1. class = “test” 인 요소 숨기기
    1. $(”.test”).hide();

 
만약 클릭 이벤트와 함께 작업을 하고싶다면 이렇게 작성할 수 있다.
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> </head> <body> <h2>버튼 눌렀을 때 p 태그 숨기기</h2> <p>p 태그 내용1</p> <p>p 태그 내용2</p> <button>클릭</button> </body> <script> $("button").click(function(){ $("p").hide(); }); </script> </html>
notion image
notion image
notion image
위에서 알아본것 처럼 “button” ← 태그 선택자 클릭하면 정의한 function$("p").hide(); 가 실행된다.
 
이때 id 는 중복이 불가능하기 때문에id 속성을 찾아 액션을 하고 싶다면
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> </head> <body> <h2>버튼 눌렀을 때 태그 숨기기</h2> <div id="test1">id 1</div> <div id="test2">id 2</div> <button id="hideId1">id 1 숨기기</button> <button id="hideId2">id 2 숨기기</button> </body> <script> $("#hideId1").click(function(){ $("#test1").hide(); }); $("#hideId2").click(function(){ $("#test2").hide(); }); </script> </html>
id 이름 별로 선택하는 방법이 있다.
 
Share article

[HootJem] 개발 기록 블로그