jQuery Interview Questions
This page consists of jQuery interview questions and answers.
To select an element by id in jQuery we use the #
sign followed by the id.
In the following example we are selecting an element having id 'super'.
var el = $("#super");
To select elements by class in jQuery we use the .
sign followed by the class.
In the following example we are selecting all the elements having class 'apple'.
var elems = $(".apple");
For this we will first select all the elements having class 'action'.
var elems = $('.action');
To add 'awesome' class name to the selected elements we will use the addClass()
method.
elems.addClass('awesome');
To remove 'not-cool' class name from the selected elements we will use the removeClass()
method.
elems.removeClass('not-cool');
So, our final jQuery code will look like the following.
var elems = $('.action');
elems.addClass('awesome');
elems.removeClass('not-cool');
For this we will use the following CSS selector div#container p
.
var elems = $('div#container p');
For this we will use the following CSS selector div#container > p
.
var elems = $('div#container > p');
For this we will first select all the elements having class 'hide-me' and then using the hide()
method we will hide them.
// first select all the elements by class
var elems = $('.hide-me');
// now hide them
elems.hide();
For this we will first select all the elements having class 'show-me' then using the show()
method we will show them.
// first select all the elements by class
var elems = $('.show-me');
// now show them
elems.show();
For this we will first select the input field using id and then using the val()
method we will get the value of the selected input field.
// select the element
var el = $('#username');
// get the value
var value = el.val();
For this we will first select the paragraph using id. Then we will use the text()
method to get the content of the paragraph.
// select the paragraph
var p = $('#description');
// get the content
var content = p.text();
For this we will first select all the paragraphs by class 'message'. Then using the text()
method we will set the content to 'Hello World'.
// select all the paragraphs having class 'message'
var elems = $('p.awesome');
// now set the message
elems.text('Hello World');
ADVERTISEMENT