jQuery DOM 요소 선택자 입문: HTML 요소를 쉽게 다루는 방법

jQuery 선택자 는 HTML 문서를 선택하기 위해 사용된다. 이미 작성한 JavaScript HTML DOM 요소 선택 다루기: getElementById, getElementsByClassName 등 포스팅의 jQuery 버전이다.

jQuery 선택자 기본 사용 방법

jQuery 선택자는 기본적으로 CSS 선택자의 문법을 따른다. 이전 JS 관련 포스팅에서 처럼 요소를 불러올 때 id 는 #을 붙이고 class 는 .(점)을 붙여 불러오는 방식을 말한다.

선택자는 $(‘CSS선택자’) 로 되어있다.

예를 들어 다음과 같은 <div> 태그로 만들어진 두 박스가 표시 되는 HTML 요소가 있다.

<!DOCTYPE html>
<html>
<head>
    <title>문서 제목</title>
</head>
<body>
<div id="redBox" class="boxs"style="width: 100px; height: 100px; background-color: red;"></div>
<div id="blueBox" class="boxs" style="width: 100px; height: 100px; background-color: blue;"></div>
<script src="jquery-3.7.1.min.js"></script>
<script>
    // JS, jQuery 코드 작성 영역
</script>
</body>
</html>
HTML

이 두 요소를 다음과 같은 방법으로 선택할 수 있다.

* 참고로 변수 명은 자유롭게 지정해도 되지만, jQuery 선택자 변수 임을 나타내기 위해 앞에 $ 를 붙이는 경우가 있다.

const $redBox = $('#redBox');
const $blueBox = $('#blueBox');

const $boxs = $('.boxs');

console.log($redBox);
console.log($blueBox);
console.log($boxs);
jQuery

콘솔에 출력 된 내용은 다음과 같다.

jQuery 선택자 콘솔 출력

태그 선택하기

CSS 선택자를 이용하므로 선택자로 태그 명을 입력하면 문서 내 태그들을 선택할 수 있다.

const $div = $('div');

console.log($div);
jQuery
jQuery 태그 선택 콘솔 출력

복수 요소의 선택

jQuery 에서 복수의 id 를 한꺼번에 선택하기 위해선 각 id 등, CSS 선택자를 쉼표(,) 로 구분하면 된다.

const $boxs = $('#redBox, #blueBox');

console.log($boxs);
jQuery
복수 요소의 선택 콘솔 출력

하위 요소 선택

jQuery 를 이용해 부모 요소 내의 하위 요소도 선택 할 수 있다. 이 때 화살괄호(>) 를 이용한다.

위의 예시 HTML 코드엔 하위 요소가 없으므로 다음 코드를 이용했다.

<!DOCTYPE html>
<html>
<head>
    <title>문서 제목</title>
</head>
<body>
<div id="redBox" class="boxs"style="width: 100px; height: 100px; background-color: red;">
    <div id="innerBox1" class="boxs"></div>
    <div id="innerBox2" class="boxs"></div>
</div>

<div id="blueBox" class="boxs"style="width: 100px; height: 100px; background-color: blue;">
    <div id="innerBox3" class="boxs"></div>
    <div id="innerBox4" class="boxs"></div>
</div>

<script src="jquery-3.7.1.min.js"></script>
<script>
const $boxs = $('#redBox > .boxs');

console.log($boxs);
</script>
</body>
</html>
HTML

출력 된 내용을 보면 red 박스 내의 boxs 클래스 들만 출력 되는 것이 확인 된다.

주의 사항

여기서 헷갈리면 안되는 점은, jQuery 선택자로 불러온 요소 jQuery 문법이 사용 가능 한 jQuery 객체 이다.이는 JS로 불러온 DOM 요소 그 자체와는 다른 것이다.

이는 jQuery 선택자로 불러오게 되면 전용 메소드를 써야지 순수 JS 메소드를 사용하지 못하는 경우도 있다. 예를 들어 다음 코드는 불러온 요소의 스타일을 변경하는 방법이다.

const $redBox = document.querySelector('#redBox');
const $blueBox = $('#blueBox');

console.log($redBox);
console.log($blueBox);

$redBox.style.backgroundColor = 'green';
//$blueBox.style.backgroundColor = 'green'; // 오류 발생
$blueBox.css('background-color', 'green'); 
jQuery

이처럼 jQuery 메소드인 .css() 를 이용해야 된다.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
목차
위로 스크롤