๋ฐ์ํ
[jQuery] class ์ฐพ๊ธฐ
hasClass()
is()
length
<div class="wrap">
<div class="apple">apple</div>
<div class="banana">banana</div>
<div class="orange">orange</div>
</div>
1.hasClass()
์ ํ์ ํ๊ทธ์ ํด๋น ์กฐ๊ฑด์ด class
์ด์ฌ์ผ ํ๋ค.
ํ๊ทธ๋ ์๋๋ ๊ฒ ๊ฐ๋ค.
// jQuery
$('.wrap > div').each(function() {
if($(this).hasClass('apple')) {
// true
$(this).css({color: 'red'});
} else {
// false
$(this).css({color: 'yellow'});
}
})
2.is()
ํน์ ํด๋์ค๋ฅผ ํฌํจํ๊ณ ์๋์ง,
class
์ธ์ id
, name
๋ฑ๋ ์ฌ์ฉ๊ฐ๋ฅํ๋ค. ํด๋์ค ์ด๋ฆ ์์ .
์ ์ฐ์ด์ ํด๋์ค ์์ฑ์์ ๋ช
์ํด์ฃผ์ด์ผ ํ๋ค.
// jQuery
$('.wrap > div').each(function() {
if($(this).is('.apple')) {
// true
$(this).css({color: 'red'});
} else {
// false
$(this).css({color: 'yellow'});
}
})
3.length
์์ฑ์ด ์กด์ฌํ๋ค๋ฉด length๋ 1์ด ๋๋ค.(true)
์กด์ฌํ์ง ์๋๋ค๋ฉด 0. (false)
length๋ฅผ ํตํด class ์์ฑ์ด ์กด์ฌํ๋์ง ์ ์ ์๋ค.
// jQuery
$('.wrap > div').each(function() {
if($('div.apple').length) {
// div ๋ชจ๋ color red
$(this).css({color: 'red'});
} else {
// ๋๋จธ์ง div๋ yellow๊ฐ ์๋๋ค.
$(this).css({color: 'yellow'});
}
})
ํด๋์ค ์ฐพ๋ ๋ฐฉ๋ฒ 3๊ฐ์ง ์ค ์ํ๋ ๋ฐฉํฅ์ ๋ง๊ฒ ๊ณจ๋ผ์ ์ฌ์ฉํ๋ ๊ฒ์ด ์ข์ ๊ฒ ๊ฐ๋ค.
Reference
Object์ ํน์ ํด๋์ค(Class) ํฌํจ ์ฌ๋ถ๋ฅผ ํ์ธํ๋ ๋ค์ํ ๋ฐฉ๋ฒ.
๋ฐ์ํ
'๐ฉ๐ปโ๐ปSTUDY > jQuery' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[jQuery] e.target / e.currentTarget / $(this) (0) | 2022.01.05 |
---|---|
[jQuery] click(), focusin() ์ด๋ฒคํธ ์ถฉ๋ (0) | 2020.07.17 |
[jQuery] :visible ์กฐ๊ฑด (1) | 2020.04.01 |
[jQuery] ํํฐ๋ง๋ฉ์๋ first() last() eq() filter() not() has() is() map() slice() (0) | 2020.02.18 |
[jQuery] on() off() one() (0) | 2020.02.13 |