1. ✅ Check if Element Exists
if ($('#myElement').length) {
console.log('Element exists!');
}
2. 🔁 Iterate Over Each Element
$('.items').each(function(index, element) {
console.log(index, $(element).text());
});
3. 🔄 Toggle Class
$('#btn').click(function() {
$('#box').toggleClass('active');
});
4. 🎯 Smooth Scroll to Element
$('html, body').animate({
scrollTop: $('#target').offset().top
}, 500);
5. 🖱️ Click Outside to Close
$(document).mouseup(function(e) {
if (!$('#popup').is(e.target) && $('#popup').has(e.target).length === 0) {
$('#popup').hide();
}
});
6. 📦 Get Data Attribute
const value = $('#item').data('value');
7. ⌨️ Trigger Function on Enter Key
$('#input').keypress(function(e) {
if (e.which === 13) {
alert('Enter pressed!');
}
});
8. 🔃 Change Element Text
$('#message').text('New message!');
9. 🧪 Validate Input Not Empty
if ($.trim($('#name').val()) === '') {
alert('Name is required!');
}
10. ⌚ Debounce Input Event
let timeout;
$('#search').on('input', function() {
clearTimeout(timeout);
timeout = setTimeout(() => {
console.log('Search:', this.value);
}, 300);
});
11. 📑 Append Element
$('#list').append('<li>New Item</li>');
12. 🧹 Empty Element
$('#content').empty();
13. 🗑️ Remove Element
$('.ad-banner').remove();
14. 🎨 Change CSS Dynamically
$('#box').css({
backgroundColor: 'blue',
fontSize: '18px'
});
15. 📏 Get Element Height
const height = $('#header').outerHeight();
16. 🛑 Prevent Default Form Submit
$('form').submit(function(e) {
e.preventDefault();
alert('Form prevented!');
});
17. 📸 Fade In Element
$('#modal').fadeIn(300);
18. 👻 Fade Out Element
$('#overlay').fadeOut(300);
19. 🔂 Slide Toggle
$('#toggle-btn').click(function() {
$('#panel').slideToggle();
});
20. 🧭 Get Selected Option Text
const selected = $('#dropdown option:selected').text();
21. 🎯 Set Input Value
$('#email').val('user@example.com');
22. 🔒 Disable a Button
$('#submitBtn').prop('disabled', true);
23. 🔓 Enable a Button
$('#submitBtn').prop('disabled', false);
24. 🎲 Randomize Array Elements
function shuffleArray(arr) {
return arr.sort(() => 0.5 - Math.random());
}
25. 📂 Clone Element
const clone = $('#template').clone().appendTo('#container');
26. 🔍 Find Child Element
const child = $('#parent').find('.child-class');
27. ⌛ Delay an Action
$('#box').fadeOut(0).delay(500).fadeIn(300);
28. 🔁 Loop Through JSON Data
const data = [{ name: 'Alice' }, { name: 'Bob' }];
$.each(data, function(i, item) {
console.log(item.name);
});
29. 🌐 Load HTML via AJAX
$('#container').load('/content.html');
30. 🔄 Send AJAX POST Request
$.post('/submit', { name: 'Parth' }, function(response) {
console.log('Success:', response);
});