What is the difference between eq() and get() methods in jQuery ?
In this article, we will discuss all the differences between eq() and get() methods in jQuery.
eq() Method: This method is used to locate the selected elements directly and returns an element with a specific index.
Syntax:
$(selector).eq(index)
Example: In this example, we will set the different text colors on the 0th and 2nd index paragraphs.
HTML
<!DOCTYPE html> < html > < head > < title >jQuery eq() Method</ title > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > </ script > </ head > < body style = "text-align: center;" > < h1 style = "color: green;" > w3wiki </ h1 > < h3 >jQuery eq() Method</ h3 > < p class = "text" >HTML</ p > < p class = "text" >CSS</ p > < p class = "text" >JavaScript</ p > < script > $(document).ready(function () { $(".text").eq(0).css("color", "red"); $(".text").eq(2).css("color", "blue"); }); </ script > </ body > </ html > |
Output:
get() method: This method loads the data from the server by using the GET HTTP request. This method returns XMLHttpRequest object.
Syntax:
$.get( url, [data], [callback], [type] )
Example: In this example, we will get the data from the server and display it on the screen. This code will run on the server.
Filename: gfg.php
PHP
<?php if ( $_REQUEST [ "name" ] ) { $name = $_REQUEST [ 'name' ]; echo "A " . $name . " portal for Beginner" ; } ?> |
Filename: index.php
HTML
<!DOCTYPE html> < html > < head > < title > CSS get() Method </ title > < script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" > </ script > </ head > < body style = "text-align: center;" > < h1 style = "color: green;" > w3wiki </ h1 > < h3 >CSS get() Method</ h3 > < div id = "GFG" > Welcome to w3wiki </ div > < br > < input type = "button" id = "Beginner" value = "Load Data" /> < script > $(document).ready(function () { $("#Beginner").click(function (event) { $.get( "gfg.php", { name: "Computer Science" }, function (data) { $('#GFG').html(data); }); }); }); </ script > </ body > </ html > |
Output:
Difference between eq() and get() methods:
jQuery eq() Method |
jQuery get() Method |
This method return the element as a jQuery object. | This method returns a DOM element. |
This method retrieves the n-1th jQuery object. | This method returns the n-1th DOM element. |
This method creates a new object from one element within the set and returns it. | This method retrieves the DOM element that matches the jQuery object. |
Its return method in an element with index of selected elements. | It helps in loading data from the server using a HTTP GET request |
Its syntax is -: $(selector).eq(index) |
Its syntax is -: $.get(URL,data,function(data,status,xhr),dataType) |
It takes one parameter as a index. | It takes one parameter as a URL. |
Contact Us