1. Selector – $()
jQuery:
const el = $('.box');
Vanilla JS:
const el = document.querySelector('.box');
2. Lặp qua danh sách phần tử
jQuery:
$('.item').each(function(index, el) {
console.log(el);
});
Vanilla JS:
document.querySelectorAll('.item').forEach((el, index) => {
console.log(el);
});
3. Gán và xóa class
jQuery:
$('.btn').addClass('active');
$('.btn').removeClass('active');
Vanilla JS:
document.querySelector('.btn').classList.add('active');
document.querySelector('.btn').classList.remove('active');
4. Gán sự kiện click
jQuery:
$('.btn').on('click', function() {
alert('Clicked!');
});
Vanilla JS:
document.querySelector('.btn').addEventListener('click', () => {
alert('Clicked!');
});
5. Gửi AJAX (GET/POST)
jQuery:
$.get('/api/data', function(response) {
console.log(response);
});
Vanilla JS (Fetch API):
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
6. Tạo phần tử mới và chèn vào DOM
jQuery:
const box = $('<div class="box">Hello</div>');
$('body').append(box);
Vanilla JS:
const box = document.createElement('div');
box.className = 'box';
box.textContent = 'Hello';
document.body.appendChild(box);
Kết luận
Viết lại jQuery sang Vanilla JS không hề khó – đặc biệt với JavaScript hiện đại. Bạn có thể tối ưu hiệu suất, giảm phụ thuộc thư viện, và học cách kiểm soát tốt hơn luồng code của mình.
Để đơn giản hóa quá trình chuyển đổi, bạn có thể viết một utility riêng cho các thao tác lặp đi lặp lại nếu cần.
Bình luận