D DevBrainBox

JQuery

JQuery Interview Questions and Answers

jQuery Interview Questions

1. What is jQuery?

A: A fast, small, cross-platform JavaScript library that simplifies HTML document traversing, event handling, animation, and Ajax interactions.

2. Why use jQuery?

A:

  • Cross-browser compatibility
  • Concise syntax
  • Easy Ajax
  • Powerful animations

3. What is the syntax to select elements?

$(selector).action();

E.g.

$('p').hide();

4. What does $ stand for?

A: The jQuery function. $ is just an alias.

5. What does $(document).ready() do?

A: Ensures code runs after DOM is fully loaded.

$(document).ready(function() {
  // code
});

or shorter:

$(function() {});

6. How to select element by ID?

$('#myId')

7. How to select by class?

$('.myClass')

8. How to select elements by attribute?

$('input[type="text"]')

9. How to select first or last element?

$('li:first')
$('li:last')

10. How to select nth element?

$('li:eq(2)') //3rd element, 0-based index

11. How to chain actions?

$('p').css('color','red').slideUp(2000).slideDown(2000);

12. How to get/set HTML content?

$('#myDiv').html('<p>New HTML</p>');

13. How to get/set text content?

$('#myDiv').text('Hello World');

14. How to get/set value of input?

$('input').val('new value');

15. How to add/remove a class?

$('p').addClass('highlight');
$('p').removeClass('highlight');

16. How to toggle class?

$('p').toggleClass('active');

17. How to append/prepend content?

$('ul').append('<li>End</li>');
$('ul').prepend('<li>Start</li>');

18. How to insert before/after?

$('p').before('<div>Before</div>');
$('p').after('<div>After</div>');

19. How to remove elements?

$('p').remove();

20. How to empty content?

$('div').empty();

21. How to handle click event?

$('button').click(function() {
  alert('Clicked!');
});

22. How to handle mouseover?

$('div').mouseover(function() {
  $(this).css('background','yellow');
});

23. How to handle multiple events?

$('p').on({
  click: function(){},
  mouseenter: function(){}
});

24. How to delegate event?

$('ul').on('click', 'li', function(){
  $(this).toggleClass('active');
});

Good for dynamically added elements.

25. How to unbind event?

$('p').off('click');

26. What is event.preventDefault()?

A: Stops default action (like following a link).

27. What is event.stopPropagation()?

A: Stops bubbling up to parent elements.

28. How to hide/show elements?

$('p').hide();
$('p').show();

29. How to toggle visibility?

$('p').toggle();

30. How to fade in/out?

$('div').fadeIn();
$('div').fadeOut();

31. How to slide up/down?

$('div').slideUp();
$('div').slideDown();

32. How to animate properties?

$('div').animate({
  left: '250px',
  opacity: 0.5
}, 1000);

33. How to stop current animation?

$('div').stop();

34. How to load data from server into element?

$('#result').load('data.txt');

35. How to perform GET request?

$.get('data.php', function(data) {
  console.log(data);
});

36. How to perform POST request?

$.post('submit.php', {name:'John'}, function(response){
  alert(response);
});

37. How to use $.ajax?

$.ajax({
  url: 'data.php',
  type: 'GET',
  dataType: 'json',
  success: function(res){ console.log(res); },
  error: function(err){ console.error(err); }
});

38. How to handle JSON data?

A: Just use dataType: 'json' and server returns JSON.

39. What is $.each?

$.each([1,2,3], function(index, value){
  console.log(index, value);
});

Iterates arrays or objects.

40. How to check if element exists?

if ($('#myId').length) { /* exists */ }

41. How to get attribute?

$('img').attr('src');

42. How to set attribute?

$('img').attr('alt', 'New Alt');

43. How to remove attribute?

$('input').removeAttr('disabled');

44. How to get position?

let pos = $('#box').offset(); // {top, left}

45. How to get dimensions?

$('div').width();
$('div').height();

46. How to create jQuery plugin?

$.fn.highlight = function() {
  this.css('background','yellow');
  return this;
};
$('p').highlight();

47. How to check jQuery version?

$.fn.jquery; // "3.6.0"

48. What are data-* attributes with jQuery?

$('div').data('id', 5); // set
$('div').data('id');    // get

49. What is chaining in jQuery?

A: Execute multiple methods on same jQuery object.

$('div').css('color','red').slideUp().slideDown();

50. Why might you still use jQuery today?

A:

  • Legacy projects
  • Rapid prototyping
  • Shortcuts for animations / Ajax without build tools
  • Wide plugin ecosystem

51. How to select even or odd elements?

$('li:even') // 0-based index
$('li:odd')

52. How to select elements that contain text?

$('p:contains("Hello")')

53. How to select visible or hidden elements?

$('div:visible')
$('div:hidden')

54. How to filter based on index?

$('li').filter(':eq(2)')

55. How to filter using a function?

$('li').filter(function(){
  return $(this).text() === "Special";
});

56. What is $.Deferred?

A: Lets you build your own promise-like workflow.

57. How to use .done, .fail, .always with Ajax?

$.get('data.json')
  .done(function(data) { console.log(data); })
  .fail(function(err) { console.error(err); })
  .always(function() { console.log('complete'); });

58. How to run multiple Ajax calls then do something?

$.when($.get('/1'), $.get('/2')).done(function(r1, r2){
  console.log(r1, r2);
});

59. How to delay animations?

$('div').slideUp(2000).delay(1000).fadeIn(2000);

60. How to clear animation queue?

$('div').clearQueue();

61. How to stop animation immediately?

$('div').stop(true, true); 
// stop + jump to end

62. Difference between .prop and .attr?

  • .attr: gets initial HTML attribute.
  • .prop: gets current property (state).
$('input').attr('checked');
 // 'checked'
$('input').prop('checked');
 // true/false

63. How to toggle property like checkbox?

$('input').prop('checked', true);

64. How to get index of element?

$('li').click(function(){
  alert( $(this).index() );
});

65. How to clone element?

$('#box').clone().appendTo('#container');

66. What is $.each vs $.map?

  • $.each: iterates over collection, returns original.
  • $.map: transforms array, returns new array.

67. How to optimize repeated selectors?

var $el = $('#bigDiv');
$el.hide();
// reuse $el

68. What is event delegation good for?

A: Handles dynamic elements without rebinding.

69. Why detach elements before manipulating?

var $el = $('#largeList').detach();
$el.find('li').removeClass('foo');
$('body').append($el);

A: Faster since detached element doesn’t trigger reflow.

70. How to minimize DOM reads?

A: Cache values.

var height = $('#box').height();
// use height repeatedly

71. How to select element with vanilla JS vs jQuery?

document.querySelector('#id') 
// vs
$('#id')

72. How to add class with vanilla JS vs jQuery?

el.classList.add('myClass'); 
// vs
$(el).addClass('myClass')

73. How to fetch data with vanilla JS?

fetch('/data').then(res => res.json());

vs jQuery

$.getJSON('/data', cb);

74. How does jQuery handle browser compatibility?

A: jQuery abstracts away differences in event models, DOM API quirks.

75. Why might you prefer React or Vue today?

A:

  • Better for complex state
  • Virtual DOM for large UIs
  • Component-based

76. How to write chainable plugin?

$.fn.highlight = function(){
  return this.each(function(){
    $(this).css('background','yellow');
  });
};
$('p').highlight();

77. How to pass options to plugin?

$.fn.myPlugin = function(options){
  var settings = $.extend({
    color: 'red'
  }, options);
  return this.css('color', settings.color);
};
$('p').myPlugin({color:'blue'});

78. How to extend jQuery globally?

$.myGlobalFunc = function(){
  alert('Hello');
}
$.myGlobalFunc();

79. How to send JSON data?

$.ajax({
  url: '/api',
  type: 'POST',
  contentType: 'application/json',
  data: JSON.stringify({x:1})
});

80. How to change default settings?

$.ajaxSetup({
  headers: { 'Authorization': 'Bearer token' }
});

81. What is $.param?

A: Serializes object into URL query string.

82. How to abort Ajax request?

var req = $.ajax(...);
req.abort();

83. How to get parent element?

$('span').parent();

84. How to get all ancestors?

$('span').parents();

85. How to get immediate children?

$('div').children('p');

86. How to get siblings?

$('li.active').siblings();

87. How to find nested elements?

$('ul').find('li');

88. How to filter selected set?

$('div').filter('.highlighted');

89. What is :input selector?

A: Selects all <input>, <select>, <textarea>, <button>.

90. How to serialize form data?

$('form').serialize();

Produces query string.

91. How to trigger native event?

$('button').trigger('click');

92. What does hover shorthand do?

$('div').hover(function(){
  $(this).addClass('over');
}, function(){
  $(this).removeClass('over');
});

93. What does toggle used to do?

A: Old jQuery toggle called functions on alternate clicks.

94. How to handle window resize?

$(window).resize(function(){
  console.log('resized');
});

95. How to detect document scroll?

$(window).scroll(function(){
  console.log($(this).scrollTop());
});

96. How to check for attribute existence?

if( $('#myDiv').attr('data-foo') !== undefined ) { }

97. How to prevent chaining from breaking?

A: Always return this; in plugins.

98. How to find element by index?

$('li').eq(2);

99. How to animate scroll?

$('html, body').animate({scrollTop: 0}, 500);

100. Why is jQuery still relevant?

  • Legacy projects
  • Quick prototyping
  • Tons of plugins
  • Simple chaining for animations and Ajax.

On this page

1. What is jQuery?2. Why use jQuery?3. What is the syntax to select elements?4. What does $ stand for?5. What does $(document).ready() do?6. How to select element by ID?7. How to select by class?8. How to select elements by attribute?9. How to select first or last element?10. How to select nth element?11. How to chain actions?12. How to get/set HTML content?13. How to get/set text content?14. How to get/set value of input?15. How to add/remove a class?16. How to toggle class?17. How to append/prepend content?18. How to insert before/after?19. How to remove elements?20. How to empty content?21. How to handle click event?22. How to handle mouseover?23. How to handle multiple events?24. How to delegate event?25. How to unbind event?26. What is event.preventDefault()?27. What is event.stopPropagation()?28. How to hide/show elements?29. How to toggle visibility?30. How to fade in/out?31. How to slide up/down?32. How to animate properties?33. How to stop current animation?34. How to load data from server into element?35. How to perform GET request?36. How to perform POST request?37. How to use $.ajax?38. How to handle JSON data?39. What is $.each?40. How to check if element exists?41. How to get attribute?42. How to set attribute?43. How to remove attribute?44. How to get position?45. How to get dimensions?46. How to create jQuery plugin?47. How to check jQuery version?48. What are data-* attributes with jQuery?49. What is chaining in jQuery?50. Why might you still use jQuery today?51. How to select even or odd elements?52. How to select elements that contain text?53. How to select visible or hidden elements?54. How to filter based on index?55. How to filter using a function?56. What is $.Deferred?57. How to use .done, .fail, .always with Ajax?58. How to run multiple Ajax calls then do something?59. How to delay animations?60. How to clear animation queue?61. How to stop animation immediately?62. Difference between .prop and .attr?63. How to toggle property like checkbox?64. How to get index of element?65. How to clone element?66. What is $.each vs $.map?67. How to optimize repeated selectors?68. What is event delegation good for?69. Why detach elements before manipulating?70. How to minimize DOM reads?71. How to select element with vanilla JS vs jQuery?72. How to add class with vanilla JS vs jQuery?73. How to fetch data with vanilla JS?74. How does jQuery handle browser compatibility?75. Why might you prefer React or Vue today?76. How to write chainable plugin?77. How to pass options to plugin?78. How to extend jQuery globally?79. How to send JSON data?80. How to change default settings?81. What is $.param?82. How to abort Ajax request?83. How to get parent element?84. How to get all ancestors?85. How to get immediate children?86. How to get siblings?87. How to find nested elements?88. How to filter selected set?89. What is :input selector?90. How to serialize form data?91. How to trigger native event?92. What does hover shorthand do?93. What does toggle used to do?94. How to handle window resize?95. How to detect document scroll?96. How to check for attribute existence?97. How to prevent chaining from breaking?98. How to find element by index?99. How to animate scroll?100. Why is jQuery still relevant?