1. jQuery 란?
- jQuery는 자바스크립트 querySelectorAll, addEventListner, classList.add 이런 것들을 이름만 훨씬 짧게 바꿔주는 라이브러리임.
2. jQuery 설치
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
- jQuery 설치한 곳 하단에서 jQuery 문법을 사용 가능
3. jQuery 사용법
- jQuery 써서 html 변경하려면
<p class="hello">안녕</p>
<script>
$('.hello').html('바보'_;
</script>
- jQuery 써서 스타일을 변경하려면
<p class="hello">안녕</p>
<script>
$('.hello').css('color', 'red');
</script>
- jQuery 써서 class 탈부착 하려면
<p class="hello">안녕</p>
<script>
$('.hello').addClass('클래스명');
$('.hello').removeClass('클래스명');
$('.hello').toggleClass('클래스명');
<script>
- jQuery써서 이벤트리스너를 사용하려면
<p class="hello">안녕</p>
<button class="test-btn">버튼</button>
<script>
$('.test-btn).on('click', function() {
!실행할 코드!
});
</script>
- jQuery써서 UI 애니메이션을 주려면
<p class="hello">안녕</p>
<button class="test-btn">버튼</button>
<script>
$('.test-btn').on('click', function(){
$('.hello').fadeOut();
});
</script>
- .hide() 는 사라지게 .fadeOut() 은 서서히 사라지게 .slideUp() 은 줄어들며 사라지게 만들어줍니다.
- 애니메이션을 반대로 주고 싶으면 show() fadeIn() slideDown() 이런게 있습니다.
- 아니면 fadeToggle() 이런 것도 있음
4. HTML 여러개를 바꾸려면
- 일반 JavaScript를 사용할 때
<p class="hello">안녕</p>
<p class="hello">안녕</p>
<p class="hello">안녕</p>
<script>
document.querySelectorAll('.hello')[0].innerHTML = '바보';
document.querySelectorAll('.hello')[1].innerHTML = '바보';
document.querySelectorAll('.hello')[2].innerHTML = '바보';
</script>
- jQuery를 사용할 때
<p class="hello">안녕</p>
<p class="hello">안녕</p>
<p class="hello">안녕</p>
<script>
$('.hello').html('바보');
</script>
- $() 셀렉터는 그냥 querySelectorAll 처럼 여러개를 전부 찾아주는데 거기에 [0] 이런식으로 순서 지정해줄 필요 없이 .html() 붙이면 셀렉터로 찾은 모든 요소를 한번에 조작하고 변경 가능