본문 바로가기
JavaScript/jQuery

jQuery) 기본 선택자, jQuery 객체 생성 방법, 가상 선택자, 순서관련 가상 선택자

by 박채니 2022. 6. 13.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


기본 선택자

 

HTML 코드

<div class="wrapper">
    <p id="p1" class="group1">안녕1</p>
    <p id="p2" class="group1" title="안녕2">안녕2</p>
    <p id="p3" class="group2">안녕3</p>
    <p id="p4" class="group2" title="안녕4">안녕4</p>
    <p id="p5" class="group1 group2">안녕5</p>
</div>
<button id="btn1">기본선택자</button>

 

jQuery 코드

btn1.addEventListener('click', () => {
    const $el = $("#p1");
    console.log($el);
});

하나의 jQuery 객체가 리턴 되었고, 그 안에는 순수 자바스크립트 객체가 들어있는 것을 확인할 수 있습니다.

즉, jQuery 객체는 순수 js객체를 감싼 객체임을 알 수 있습니다.

 

이를 이용하여 css 설정을 해줄 수도 있습니다.

 

css()

- style 설정

$el.css('color', 'red');

 

jQuery 객체 안에 여러개의 js객체를 감쌀 수도 있습니다.

const $group1 = $(".group1");
console.log($group1);

 

여러개의 js 객체 css 설정하기

console.log(
    $group1.css('color', 'blue').css('font-size', '24px')
)

실제 js 요소 각각에 style을 지정하는 것을 확인할 수 있습니다.

또한, 메소드의 리턴 값이 다시 jQuery 객체이므로 연달아 메소드 호출이 가능합니다. (method chaining)

console에 출력하니 또 jQuery 객체가 리턴되는 것을 확인할 수 있습니다.

console.log(
    $group1.css('color', 'blue').css('font-size', '24px') === $group1
);

 

jQuery를 사용하지 않다면, 각 요소에 직접 접근하여 제어해줘야겠죠?

document.querySelectorAll(".group1").forEach((group) => group.style.color = 'pink');

 

title 속성을 가진 요소들 css 적용하기

$("[title]").css('text-decoration', 'underline');

 


jQuery 객체 생성 방법

① selector 문자열

② js 객체

 

HTML 코드

<button id="btn2">jQuery객체</button>

 

jQuery 코드

btn2.addEventListener('click', () => {
    $(p4).css('background-color', 'yellow');
});

전달된 p4는 document.querySelector("#p4")가 전달 될 것이고, $("#p4")한 것과 동일한 결과를 나타냅니다.

 

여러개의 id값 css 적용하기

$("#p1,#p2,#p3").css('color', 'springgreen');

 

js와 jQuery 혼합

const group2 = document.querySelector(".group2");
$(group2).css('text-decoration', 'line-through');

위처럼 사용할 수도 있습니다.

 


가상 선택자

 

HTML 코드

<fieldset>
    <legend>input</legend>
    <input type="text" placeholder="text">
    <input type="password" placeholder="password">
    <br>
    <input type="radio">
    <input type="checkbox">
    <input type="button" value="버튼">
    <br>
    <input type="button" id="btn3" value="가상선택자">
</fieldset>

 

jQuery 코드

 

이벤트 이름에 해당하는 메소드가 존재! → 이벤트 핸들러

$(btn3).click((e) => {

});

 

type 가상 선택자

:type

$(btn3).click((e) => {
    $(":text,:password").css('background-color', 'tomato').css('color', '#fff');
});

"[type=text],[type=password]"도 가능하지만 ":text,:password"로 가상 선택자를 사용할 수 있습니다.

 

$(":radio,:checkbox").prop('checked', true);

prop속성을 이용하여 동적으로 check박스를 컨트롤 할 수도 있습니다.

 

val()

- getter

console.log($(":button:eq(2)").val());  //getter

input 박스 외에도 위에 button 속성이 2개 더 있어서 eq()가 없다면, 0번지 button의 value값을 가져오게 되므로,

eq()를 지정하여 2번지 button의 value값을 가져오게 하였습니다.

 

- setter

$(":button:eq(2)").val('Button');   // setter

button의 value가 설정한 'Button'으로 변경된 것을 확인할 수 있습니다.

 


순서관련 가상 선택자

 

HTML 코드

<table id="people">
    <thead>
    <tr>
        <th>이름</th>
        <th>혈액형</th>
        <th>주소</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>홍길동</td>
        <td>A</td>
        <td>서울시 강남구</td>
    </tr>
    <tr>
        <td>신사임당</td>
        <td>AB</td>
        <td>서울시 강서구</td>
    </tr>
    <tr>
        <td>장영실</td>
        <td>B</td>
        <td>서울시 강북구</td>
    </tr>
    <tr>
        <td><a href="#">이순신</a></td>
        <td>O</td>
        <td>서울시 강동구</td>
    </tr>
    </tbody>
    <tfoot>
    <tr>
        <th colspan="2">총원</th>
        <td>4명</td>
    </tr>
    </tfoot>
</table>
<button id="btn4">확인</button>

 

jQuery 코드

 

:odd

- 홀수

$(btn4).click((e) => {
    let $selected;

    $selected = $("#people tr:odd")

    $selected.css({
        'background-color' : 'gray',
        'color' : '#fff'
    });
})

홀수 행에 한하여 css가 적용된 것을 확인할 수 있습니다.

 

:even

- 짝수

let $selected;

$selected = $("#people tr:even")

$selected.css({
    'background-color' : 'gray',
    'color' : '#fff'
});

짝수 행에 한하여 css가 적용된 것을 확인할 수 있습니다.

 

:first

(:first-child, :first-of-type)

let $selected;

$selected = $("#people tr:first")

$selected.css({
    'background-color' : 'gray',
    'color' : '#fff'
});

첫번째 요소에 한하여 css가 적용된 것을 확인할 수 있습니다.

 

:last

(:last-child, :last-of-type)

let $selected;

$selected = $("#people tr:last")

$selected.css({
    'background-color' : 'gray',
    'color' : '#fff'
});

마지막 요소에 한하여 css가 적용된 것을 확인할 수 있습니다.

 

:eq(index)

- index 요소

let $selected;

$selected = $("#people tr:eq(1)")

$selected.css({
    'background-color' : 'gray',
    'color' : '#fff'
});

1번지 요소에 한하여 css가 적용된 것을 확인할 수 있습니다.

 

:gt(index)
- index보다 큰

let $selected;

$selected = $("#people tr:gt(0)")

$selected.css({
    'background-color' : 'gray',
    'color' : '#fff'
});

0번지보다 큰 요소들에 한하여 css가 적용된 것을 확인할 수 있습니다.

 

:lt(index)

- index보다 작은

let $selected;

$selected = $("#people tr:lt(5)")

$selected.css({
    'background-color' : 'gray',
    'color' : '#fff'
});

5번지보다 작은 요소들에 한하여 css가 적용된 것을 확인할 수 있습니다.

 

:contains(text)

- 자식요소 textnode 포함 여부

let $selected;

$selected = $("#people tr:contains('A')");  // TextNode

$selected.css({
    'background-color' : 'gray',
    'color' : '#fff'
});

TextNode에서 'A'를 포함하고 있는 요소들에 한하여 css가 적용된 것을 확인할 수 있습니다.

 

:has(selector)
- 자식요소 selector 포함 여부

let $selected;

$selected = $("#people tr:has(a)")

$selected.css({
    'background-color' : 'gray',
    'color' : '#fff'
});

'a' 태그를 포함하고 있는 요소들에 한하여 css가 적용된 것을 확인할 수 있습니다.

 

 

'JavaScript > jQuery' 카테고리의 다른 글

jQuery) attr과 prop  (0) 2022.06.13
jQuery) jQuery 다운로드, load 이벤트  (0) 2022.06.13