3.2 Usage of Jquery
3.2 Usage of Jquery
Learning outcome1:
CHAP XII:
Use of JavaScript Libraries
Usage of jQuery
Table of Contents
1. Usage of jquery ............................................................................................................. 3
1.1. Introduction ............................................................................................................................ 3
1.1.1. What You Should Already Know ..................................................................................... 3
1.1.2. Why jQuery? ................................................................................................................... 3
1.1.3. Will jQuery work in all browsers? ................................................................................... 3
1.2. Jquery basic ............................................................................................................................. 3
1.2.1. Adding jQuery library to a Web Pages ............................................................................ 3
1.2.2. jQuery Syntax .................................................................................................................. 4
1.2.3. The Document Ready Event ............................................................................................ 4
1.2.4. jQuery Selectors .............................................................................................................. 5
1.3. jQuery Event Methods ............................................................................................................ 5
1.4. jQuery Effect Methods ............................................................................................................ 7
1.5. Jquery manipulation ............................................................................................................... 8
1.5.1. jQuery DOM Manipulation.............................................................................................. 8
1.5.2. Manipulate HTML Attributes using jQuery ..................................................................... 8
1.5.3. Manipulate DOM Element's Dimensions using jQuery ................................................... 8
1.5.4. Traversing DOM Elements using jQuery ......................................................................... 9
1.5.5. CSS Manipulation using jQuery ....................................................................................... 9
1.5.6. jQuery Animations ........................................................................................................ 10
1.6. Jquery advanced ................................................................................................................... 10
1.6.1. jQuery AJAX Introduction.............................................................................................. 10
1.6.2. jQuery ajax() Method .................................................................................................... 11
1.6.3. jQuery get() Method ..................................................................................................... 15
1.6.4. jQuery post() Method ................................................................................................... 17
1.6.5. jQuery load() Method ................................................................................................... 19
1.7. Exercises ................................................................................................................................ 20
1. Usage of jquery
1.1. Introduction
Before you start studying jQuery, you should have a basic knowledge of HTML, CSS, JavaScript
There are lots of other JavaScript libraries out there, but jQuery is probably the most popular, and
also the most extendable. Many of the biggest companies on the Web use jQuery, such as Google,
Microsoft, IBM, Netflix
The jQuery team knows all about cross-browser issues, and they have written this knowledge into
the jQuery library. jQuery will run exactly the same in all major browsers.
There are several ways to start using jQuery on your web site. You can:
Download the jQuery library from jQuery.com
Include jQuery from a CDN, like Google
The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice
that the <script> tag should be inside the <head> section)
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js">
</script>
</head>
1.2.2. jQuery Syntax
With jQuery you select (query) HTML elements and perform "actions" on them. The jQuery syntax is
tailor-made for selecting HTML elements and performing some action on the element(s).
Examples:
You might have noticed that all jQuery methods in our examples, are inside a document ready event
$(document).ready(function () {
// jQuery methods go here...
});
This is to prevent any jQuery code from running before the document is finished loading (is ready).
It is good practice to wait for the document to be fully loaded and ready before working with it. This
also allows you to have your JavaScript code before the body of your document, in the head section.
Here are some examples of actions that can fail if methods are run before the document is fully
loaded:
The jQuery team has also created an even shorter method for the document ready event:
$(function () {
// jQuery methods go here...
});
1.2.4. jQuery Selectors
jQuery selectors are one of the most important parts of the jQuery library. They allow you to select
and manipulate HTML element(s). They are used to "find" (or select) HTML elements based on their
name, id, classes, types, attributes, values of attributes and much more. It's based on the existing
CSS Selectors, and in addition, it has some own custom selectors.
All selectors in jQuery start with the dollar sign and parentheses: $().
Syntax Description
$("p") Element
$("#test") id selector
$(".test") class selector
$("*") Selects all elements
$(this) Selects the current HTML element
$("p.intro") Selects all <p> elements with class="intro"
$("p:first") Selects the first <p> element
$("ul li:first") Selects the first <li> element of the first <ul>
$("ul li:first-child") Selects the first <li> element of every <ul>
$("[href]") Selects all elements with an href attribute
Selects all <a> elements with a target attribute value equal to
$("a[target='_blank']")
"_blank"
Selects all <a> elements with a target attribute value NOT equal
$("a[target!='_blank']")
to "_blank"
Selects all <button> elements and <input> elements of
$(":button")
type="button"
$("tr:even") Selects all even <tr> elements
$("tr:odd") Selects all odd <tr> elements
Event methods trigger or attach a function to an event handler for the selected elements. The
following table lists all the jQuery methods used to handle events.
The following table lists all the jQuery methods for creating animation effects.
Method Description
animate() Runs a custom animation on the selected elements
clearQueue() Removes all remaining queued functions from the selected elements
delay() Sets a delay for all queued functions on the selected elements
dequeue() Removes the next function from the queue, and then executes the function
fadeIn() Fades in the selected elements
fadeOut() Fades out the selected elements
fadeTo() Fades in/out the selected elements to a given opacity
fadeToggle() Toggles between the fadeIn() and fadeOut() methods
finish() Stops, removes and completes all queued animations for the selected elements
hide() Hides the selected elements
queue() Shows the queued functions on the selected elements
show() Shows the selected elements
slideDown() Slides-down (shows) the selected elements
slideToggle() Toggles between the slideUp() and slideDown() methods
slideUp() Slides-up (hides) the selected elements
stop() Stops the currently running animation for the selected elements
toggle() Toggles between the hide() and show() methods
jQuery provides various methods to add, edit or delete DOM element(s) in the HTML page. The
following table lists some important methods to add/remove new DOM elements.
Method Description
append() Inserts content to the end of element(s) which is specified by a selector.
Inserts content (new or existing DOM elements) before an element(s) which is
before()
specified by a selector.
Inserts content (new or existing DOM elements) after an element(s) which is
after()
specified by a selector.
prepend() Insert content at the beginning of an element(s) specified by a selector.
remove() Removes element(s) from DOM which is specified by selector.
replaceAll() Replace target element(s) with specified element.
wrap() Wrap an HTML structure around each element which is specified by selector.
The following table lists jQuery methods to get or set value of attribute, property, text or html.
The jQuery library includes various methods to manipulate DOM element's dimensions like height,
width, offset, position etc. The following table lists all the jQuery methods to get or set DOM
element's dimensions.
Method Description
The jQuery library includes various methods to traverse DOM elements in a DOM hierarchy. The
following table lists jQuery methods for traversing DOM elements.
Methods Description
children() Get all the child elements of the specified element(s)
Iterate over specified elements and execute specified call back function for each
each()
element.
find() Get all the specified child elements of each specified element(s).
first() Get the first occurrence of the specified element.
next() Get the immediately following sibling of the specified element.
parent() Get the parent of the specified element(s).
prev() Get the immediately preceding sibling of the specified element.
siblings() Get the siblings of each specified element(s)
The jQuery library includes various methods to manipulate style properties and CSS class of DOM
element(s). The following table lists jQuery methods for styling and css manipulation.
Methods Description
jQuery includes methods which give special effects to the elements on hiding, showing,
changing style properties, and fade-in or fade-out operation. These special effect methods can
be useful in building an interactive user interface. The following table lists jQuery methods for
adding special effects to the DOM elements.
AJAX stands for "Asynchronous JavaScript and XML". JavaScript includes features of sending
asynchronous http request using XMLHttpRequest object. Ajax is about using this ability of JavaScript
to send asynchronous http request and get the xml data as a response (also in other formats) and
update the part of a web page (using JavaScript) without reloading or refreshing entire web page.
The jQuery library includes various methods to send Ajax requests. These methods internally use
XMLHttpRequest object of JavaScript. The following table lists all the Ajax methods of jQuery.
jQuery Ajax
Description
Methods
ajax() Sends asynchronous http request to the server.
get() Sends http GET request to load the data from the server.
Post() Sends http POST request to submit or load the data to the server.
getJSON() Sends http GET request to load JSON encoded data from the server.
Sends http GET request to load the JavaScript file from the server and then
getScript()
executes it.
Sends http request to load the html or text content from the server and add
load()
them to DOM element(s).
The jQuery library also includes following events which will be fired based on the state of the Ajax
request.
jQuery Ajax
Description
Events
ajaxComplete() Register a handler function to be called when Ajax requests complete.
Register a handler function to be called when Ajax requests complete with an
ajaxError()
error.
ajaxSend() Register a handler function to be called before Ajax request is sent.
ajaxStart() Register a handler function to be called when the first Ajax request begins.
Register a handler function to be called when all the Ajax requests have
ajaxStop()
completed.
Register a handler function to be called when Ajax request completes
ajaxSuccess()
successfully.
The jQuery ajax() method provides core functionality of Ajax in jQuery. It sends asynchronous HTTP
requests to the server. Syntax: $.ajax(url); or $.ajax(url,[options]);
Parameter description:
url: A string URL to which you want to submit or retrieve the data
options: Configuration options for Ajax request. An options parameter can be specified using
JSON format. This parameter is optional.
The following table list all the options available for configuring Ajax request.
Options Description
The content type sent in the request header that tells the server what kind of
accepts
response it will accept in return.
By default, all requests are sent asynchronously. Set it false to make it
async
synchronous.
beforeSend A callback function to be executed before Ajax request is sent.
cache A boolean indicating browser cache. Default is true.
complete A callback function to be executed when request finishes.
A string containing a type of content when sending MIME content to the
contentType
server.Default is "application/x-www-form-urlencoded; charset=UTF-8"
crossDomain A boolean value indicating whether a request is a cross-domain.
data A data to be sent to the server. It can be JSON object, string or array.
dataType The type of data that you're expecting back from the server.
error A callback function to be executed when the request fails.
A Boolean indicating whether to trigger a global Ajax request handler or not.
global
Default is true.
headers An object of additional header key/value pairs to send along with request.
Allow the request to be successful only if the response has changed since the last
ifModified
request. This is done by checking the Last-Modified header. Default value is false.
isLocal Allow the current environment to be recognized as local.
Override the callback function name in a JSONP request. This value will be used
jsonp
instead of 'callback' in the 'callback=?' part of the query string in the url.
jsonpCallback String containing the callback function name for a JSONP request.
mimeType String containing a mime type to override the XMLHttpRequest mime type.
A password to be used with XMLHttpRequest in response to an HTTP access
password
authentication request.
A Boolean indicating whether data assigned to data option will be converted to a
processData
query string. Default is true.
A JSON object containing numeric HTTP codes and functions to be called when
statusCode
the response has the corresponding code.
success A callback function to be executed when Ajax request succeeds.
timeout A number value in milliseconds for the request timeout.
type A type of http request e.g. POST, PUT and GET. Default is GET.
url A string containing the URL to which the request is sent.
A username to be used with XMLHttpRequest in response to an HTTP access
username
authentication request.
xhr A callback for creating the XMLHttpRequest object.
An object of fieldName-fieldValue pairs to set on the native XMLHttpRequest
xhrFields
object.
Let's see how to send http requests using $.ajax() (or jQuery.ajax()) method.
Send Ajax Request
The ajax() methods performs asynchronous http request and gets the data from the server. The
following example shows how to send a simple Ajax request.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#ajaxBtn').click(function () {
$.ajax('/jquery/getdata', // request url
{
success: function (data, status, xhr) {// success callback function
$('p').append(data);
In the above example, first parameter '/getData' of ajax() method is a url from which we want to
retrieve the data. The second parameter is options parameter in JSON format where we have
specified callback function that will be executed when request succeeds. You can configure other
options as mentioned in the above table. By default ajax() method performs http GET request if
option parameter does not include method option.
<script type="text/javascript">
$(document).ready(function () {
$('#ajaxBtn').click(function () {
$.ajax('/jquery/getjsondata',
{
dataType: 'json', // type of response data
timeout: 500, // timeout milliseconds
success: function (data, status, xhr) { // success callback function
$('p').append(data.firstName + ' ' + data.middleName + ' ' + data.lastName);
},
error: function (jqXhr, textStatus, errorMessage) { // error callback
$('p').append('Error: ' + errorMessage);
}
});
In the above example, first parameter is a request url which will return JSON data. In the options
parameter, we have specified dataType and timeout options. The dataType option specifies the type
of response data, in this case it is JSON. The timeout parameter specifies request timeout in
milliseconds. We have also specified callback functions for error and success.
The ajax() method returns an object of jQuery XMLHttpRequest. The following example shows how
to use jQuery XMLHttpRequest object.
The ajax() method can send all type of http requests. The following example sends http POST
request to the server.
$.ajax('/jquery/submitData', {
type: 'POST', // http method
data: { myData: 'This is my data.' }, // data to submit
success: function (data, status, xhr) {
$('p').append('status: ' + status + ', data: ' + data);
},
error: function (jqXhr, textStatus, errorMessage) {
$('p').append('Error' + errorMessage);
}
});
<p></p>
In the above example, first parameter is a url which is used to submit the data. In the options
parameter, we have specified a type option as a POST, so ajax() method will send http POST request.
Also, we have specified data option as a JSON object containing data which will be submitted to the
server. So this way you can send GET, POST or PUT request using ajax() method.
Points to Remember :
$.ajax() method allows you to send asynchronous http requests to submit or retrieve data
from the server without reloading the whole page.
$.ajax() can be used to send http GET, POST, PUT, DELETE etc. request. It can retrieve any
type of response from the server.
Syntax: $.ajax(url,[options])
Use option parameter to customize ajax request as per your need.
The jQuery get() method sends asynchronous http GET request to the server and retrieves the data.
Syntax: $.get(url, [data],[callback]);
Parameters Description:
url: request url from which you want to retrieve the data
data: data to be sent to the server with the request as a query string
callback: function to be executed when request succeeds
The following example shows how to retrieve data from a text file.
$.get('/data.txt', // url
function (data, textStatus, jqXHR) { // success callback
alert('status: ' + textStatus + ', data:' + data);
});
In the above example, first parameter is a url from which we want to retrieve the data. Here, we
want to retrieve data from a txt file located at mydomain.com/data.txt. Please note that you don't
need to give base address.
The second parameter is a callback function that will be executed when this GET request succeeds.
This callback function includes three parameters data, textStatus and jQuery wrapper of
XMLHttpRequest object. Data contains response data, textStatus contains status of request and
jqXHR is a jQuery XMLHttpRequest object which you can use for further process.
The following example shows how to retrieve JSON data using get() method
The second parameter is data to be sent to the server as a query string. We have specified name
parameter with value 'Steve' in the JSON format. So now, the request url would look like
http://mydomain.com/jquery/getjsondata?name=Steve. The third parameter is a callback function
that will be executed when this GET request succeeds.
jQuery getJSON() Method
The jQuery getJSON() method sends asynchronous http GET request to the server and retrieves the
data in JSON format by setting accepts header to application/json, text/javascript. This is same as
get() method, the only difference is that getJSON() method specifically retrieves JSON data whereas
get() method retrieves any type of data. It is like shortcut method to retrieve JSON data.
Syntax: $.getJSON(url,[data],[callback]);
Parameter Description:
url: request url from which you want to retrieve the data
data: JSON data to be sent to the server as a query string
callback: function to be executed when request succeeds
The following example shows how to retrieve JSON data using getJSON() method.
In the above example, first parameter is a url from which we want to get JSON data. This can be a
web service or any other url that returns JSON data.
The second parameter is data to pass as query string with the GET request. So now, the request url
would look like http://mydomain.com/jquery/getjsondata?name=Steve. The third parameter is a
callback function which will be executed when request succeeds. The data parameter will be in the
JSON format because getJson() method automatically converts server response into a JSON object.
You can attach fail and done callback methods to getJson() method as shown below.
$.getJSON('/jquery/getjsondata', { name:'Steve'}, function(data, textStatus, jqXHR){
alert(data.firstName);
})
.done(function () { alert('Request done!'); })
.fail(function (jqxhr,settings,ex) { alert('failed, '+ ex); });
The jQuery getScript() method sends http GET request to the server, retrieves the JavaScript file and
then executes it. Internally, jQuery getScript() method calls get() method and sets dataType to script.
Syntax: $.getScript(url, [callback]);
Parameter Description:
url: request url from which you want to download JavaScript file
callback: function to be executed when request succeeds
The following example shows how to download script file using getScript() method.
$.getScript('/Scripts/myJavaScriptFile.js', function(script,status,jqxhr){
alert(status);
});
In the above example, first parameter is a url from which we want to download script file. Here, we
download myJavaScriptFile.js file for demo purpose. The second parameter is a callback function
which will be executed when request succeeds. Thus, you can use different get methods to retrieve
different types of resources using http get request.
Points to Remember :
$.get(), $.getJSON() method allows you to send asynchronous http GET request to retrieve
the data from the server without reloading whole page.
$.get() can be used to retrieve any type of response from the server.
$.getJSON() method is a short form method to retrieve JSON response from the server.
$.getScript() sends asynchronous http GET request to retrieve the script files from the server
and execute it.
Syntax:
o $.get(url,[data],[callback])
o $.getJSON(url,[data],[callback])
o $.getScript(url,[callback])
The jQuery post() method sends asynchronous http POST request to the server to submit the data to
the server and get the response.
Syntax: $.post(url,[data],[callback],[type]);
Parameter Description:
url: request url from which you want to submit & retrieve the data.
data: json data to be sent to the server with request as a form data.
callback: function to be executed when request succeeds.
type: data type of the response content.
Let's see how to submit data and get the response using post() method. Consider the following
example.
$.post('/jquery/submitData', // url
{ myData: 'This is my data.' }, // data to be submitted
function (data, status, jqXHR) {// success callback
$('p').append('status: ' + status + ', data: ' + data);
})
< p ></p >
In the above example, first parameter is a url to which we want to send http POST request and
submit the data.
The second parameter is a data to submit in JSON format, where key is the name of a parameter and
value is the value of parameter.
The third parameter is a success callback function that will be called when request succeeds. The
callback function can have three parameters; data, status and jqXHR. The data parameter is a
response coming from the server. The following example shows how to submit and retrieve JSON
data using post() method.
$.post('/submitJSONData', // url
{ myData: 'This is my data.' }, // data to be submit
function (data, status, xhr) { // success callback function
alert('status: ' + status + ', data: ' + data.responseData);
},
'json'); // response data format
In the above example, please notice that last parameter is a type of response data. We will get JSON
data as a server response. So post() method will automatically parse response into JSON object. Rest
of the parameters are same as first example. You can also attach fail and done callback methods to
post() method as shown below.
$.post('/jquery/submitData',
{ myData: 'This is my data.' },
function(data, status, xhr) {
<p></p>
Points to Remember :
$.post() method allows you to send asynchronous http POST request to submit and retrieve
the data from the server without reloading whole page.
Syntax: $.post(url,[data],[callback],[type])
Specify type parameter for the type of response data e.g. specify 'JSON' if server return JSON
data.
Internally post() method calls ajax() method only by passing method='POST' as option.
1.6.5. jQuery load() Method
The jQuery load() method allows HTML or text content to be loaded from a server and added into a
DOM element.
Syntax: $.load(url,[data],[callback]);
Parameters Description:
url: request url from which you want to retrieve the content
data: JSON data to be sent with request to the server.
callback: function to be executed when request succeeds
The following example shows how to load html content from the server and add it to div element.
$('#msgDiv').load('/demo.html');
<div id="msgDiv"></div>
In the above example, we have specified html file to load from the server and add its content to the
div element.
Note : If no element is matched by the selector then Ajax request will not be sent.
The load() method allows us to specify a portion of the response document to be inserted into DOM
element. This can be achieved using url parameter, by specifying selector with url separated by one
or multiple space characters as shown in the following example.
$('#msgDiv').load('/demo.html #myHtmlContent');
<div id="msgDiv"></div>
In the above example, content of the element whose id is myHtmlContent, will be added into
msgDiv element. The following is a demo.html.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<h1>This is demo html page.</h1>
<div id="myHtmlContent">This is my html content.</div>
</body>
</html>
The load() method also allows us to specify data to be sent to the server and fetch the data.
$('#msgDiv').load('getData', // url
{ name: 'bill' }, // data
function (data, status, jqXGR) { // callback function
alert('data loaded')
});
<div id="msgDiv"></div>
In the above example, first parameter is a url from which we want to fetch the resources. The
second parameter is data to be sent to the server. The third parameter is a callback function to
execute when request succeeds.
Points to Remember :
$.load() method allows HTML or text content to be loaded from a server and added into a
DOM element.
Syntax:$.post(url,[data],[callback])
Specify selector with url to specify a portion of the response document to be inserted into
DOM element. $('#msgDiv').load('/demo.html #myHtmlContent');
1.7. Exercises
Exercises
1. How do you add the jQuery library to a web page?
There are two ways to add the jQuery library to a web page:
Inline: You can add the jQuery library code directly to the web page, between the <head>
and </head> tags.
External: You can download the jQuery library file from the jQuery website and link to it
from your web page.
$(document).ready(function() {
// Your code here
});
//Alternatively, you can use the shorthand notation:
$(function() {
// Your code here
});
$('#myButton').on('click', function() {
// Code to execute when the button is clicked
alert('Button clicked!');
});
$('a').on('click', function(event) {
// Prevent the default behavior of the click event (navigation)
event.preventDefault();
alert('Link clicked, but navigation prevented.');
});
9. How do you create sliding animations using jQuery?
jQuery provides methods like .slideUp(), .slideDown(), and .slideToggle() to create sliding
animations that hide or show elements by adjusting their height.
$(document).ready(function() {
// Slide down an element with a specified duration
$('#slideDownButton').click(function() {
$('#slideDownElement').slideDown(1000);
});
// Slide-up element with specified duration and a callback function
$('#slideUpButton').click(function() {
$('#slideUpElement').slideUp(1000, function() {
alert('Element slid up!');
});
});
// Slide toggle an element with a specified duration
$('#slideToggleButton').click(function() {
$('#slideToggleElement').slideToggle(1000);
});
});
10. How can you append new content to an HTML element using jQuery?
You can use the .append() method in jQuery to add new content, such as text, HTML, or other
elements, to the end of a selected element.
$(document).ready(function() {
$('#targetElement').append('<p>New content added using
jQuery.</p>');
});
11. How do you change the text content of an HTML element using jQuery?
To change the text content of an HTML element, you can use the .text() method in
jQuery.
$(document).ready(function() {
$('#myElement').text('New text content using jQuery.');
});
12. How can you modify the attributes of an HTML element using jQuery?
You can use the .attr() method in jQuery to modify the attributes of an HTML element.
This method allows you to get or set attributes like src, href, class, and more.
$(document).ready(function() {
// Get the value of an attribute
var linkHref = $('#myLink').attr('href');
console.log('Current link href:', linkHref);
13. How do you retrieve the value of an HTML attribute using jQuery?
You can use the .attr() method in jQuery to retrieve the value of an HTML attribute from a
selected element.
$(document).ready(function() {
var imageUrl = $('#myImage').attr('src');
console.log('Image source:', imageUrl);
});
15. How can you animate changes in an element's dimensions using jQuery?
You can use the .animate() method in jQuery to create animations, including changing the
dimensions (width and height) of an element.
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
16. Is it possible to manipulate ALL CSS properties with the animate() method?
Yes, almost! However, there is one important thing to remember: all property names
must be camel-cased when used with the animate() method: You will need to write
paddingLeft instead of padding-left, marginRight instead of margin-right, and so on.
Also, color animation is not included in the core jQuery library.
17. How can you adjust an element's dimensions based on its current dimensions using
jQuery?
You can use the .width() and .height() methods with functions as arguments to adjust an
element's dimensions based on its current dimensions.
$(document).ready(function(){
$('button').click(function() {
$('div').width(function(index, currentWidth) {
return currentWidth * 1.5; // Increase width by 50%
});
$('div').height(function(index, currentHeight) {
return currentHeight * 0.8; // Reduce height by 20%
});
});
});
18. How can you find the parent element of a selected element using jQuery?
You can use the .parent() method in jQuery to traverse up the DOM and select the direct
parent element of a selected element.
19. How do you find all the child elements of a selected element using jQuery?
You can use the .children() method in jQuery to select all the direct child elements of a
selected element.
$(document).ready(function() {
var childElements = $('#parentElement').children();
childElements.css('background-color', 'yellow');
});
20. How can you traverse to the siblings of a selected element using jQuery?
You can use the .siblings() method in jQuery to select all the siblings (elements with the
same parent) of a selected element.
$(document).ready(function() {
var siblingElements = $('#selectedElement').siblings();
siblingElements.css('font-weight', 'bold');
});
jQuery provides various methods for traversing DOM elements, such as .parent(),
.children(), .siblings(), .next(), .prev(), and more.
21. What is the jQuery .ajax() method used for?
The .ajax() method in jQuery is used to perform asynchronous HTTP requests to a server.
It provides a way to send and receive data from a server without requiring a page refresh,
making it ideal for creating dynamic and interactive web applications.
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
22. How do you send data to the server using the jQuery .ajax() method?
You can send data to the server using the data option in the .ajax() method. This is
commonly used with HTTP methods like POST.
$.ajax({
url: 'https://api.example.com/submit',
method: 'POST',
data: {
username: 'john_doe',
email: 'john@example.com'
},
success: function(response) {
console.log('Data submitted:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
23. How can you set headers and handle cross-origin requests using the jQuery .ajax()
method?
You can set custom headers and handle cross-origin requests using the headers option in
the .ajax() method. This is useful for sending authorization tokens, handling CORS (Cross-
Origin Resource Sharing), and more.
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
headers: {
'Authorization': 'Bearer your_token'
},
crossDomain: true,
success: function(response) {
console.log('Data received:', response);
},
error: function(xhr, status, error) {
console.error('Error:', error);
}
});
25. How can you pass query parameters with the jQuery .get() method?
You can pass query parameters to the server by including them in the URL of the .get()
method. Query parameters are used to send additional information to the server.
var userId = 123;
$.get('https://api.example.com/user', { id: userId },
function(response) {
console.log('User data:', response);
});
26. How do you handle errors when using the jQuery .get() method?
The .get() method provides an optional second argument for handling errors using a
callback function. This function is executed if the request encounters an error.
$.get('https://api.example.com/data', function(response) {
console.log('Data received:', response);
}, function(error) {
console.error('Error:', error.statusText);
});
27. What is the purpose of the jQuery .post() method?
The .post() method in jQuery is used to send an HTTP POST request to a server to submit
data and retrieve a response. It's commonly used when you need to send data to the
server for processing or database operations.
$.post('https://api.example.com/submit', { username: 'john_doe',
email: 'john@example.com' }, function(response) {
console.log('Response:', response);
});
28. How can you send JSON data using the jQuery .post() method?
You can send JSON data using the .post() method by setting the appropriate headers and
specifying the data format as JSON.
var jsonData = {
name: 'Alice',
age: 28,
city: 'New York'
};
$.post('https://api.example.com/submit', JSON.stringify(jsonData),
function(response) {
console.log('Response:', response);
}, 'json');
29. How can you handle errors when using the jQuery .post() method?
Similar to other jQuery AJAX methods, the .post() method provides an optional third
argument to handle errors using a callback function.
$.post('https://api.example.com/submit', { data: 'value' },
function(response) {
console.log('Response:', response);
}, 'json')
.fail(function(error) {
console.error('Error:', error.statusText);
});
31. How can you pass data to the server using the jQuery .load() method?
You can pass data to the server while using the .load() method by including data
parameters in the URL or by specifying data using the second argument.
$('#result').load('https://api.example.com/data',
{ type: 'json', limit: 10 });
32. How can you execute a callback function after loading content using the jQuery .load()
method?
You can provide a callback function as the second argument to the .load() method. This
function will be executed after the content is loaded and inserted into the selected
element.
$('#result').load('https://api.example.com/data', function(response,
status, xhr) {
if (status === 'success') {
console.log('Content loaded successfully.');
} else {
console.error('Failed to load content.');
}
});