The is
of JQuery serves to check if the selected element corresponds to a given element.
This function can be called by passing different parameters:
Passing a selector
When you pass a selector, is
checks to see if the element you have corresponds to the last selector. A simple example of this would be $(this).is(".premiado")
that checks whether the current element, $(this)
, corresponds to the premiado
class. It is important to mention that the selector can be much more elaborate including all kinds of selectors supported in both JQuery and CSS3.
Example of is
based on a class:
$("li").on("click", function(){
if ($(this).is(".premiado")){
console.log("li premiado!");
}
else {
console.log("li normal");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Cliquenosváriosli's<ul><li>1</li><li>2</li><liclass="premiado">3 (premiado)</li>
<li>4</li>
<li>5</li>
</ul>
Passing an Object
You can also check if one element corresponds to another element that you have stored in an object. This usually means that you have previously saved a element with something like let elemento = $(this);
into a variable and then later it tests whether it corresponds to $(...).is(elemento)
.
With the passing of an object is easy to set an example that tells you if you clicked the last element or a different:
let ultimo;
$("li").on("click", function(){
if ($(this).is(ultimo)){
console.log("li é o mesmo que o anterior");
}
else {
console.log("li diferente");
}
ultimo = $(this); //o ultimo passa a ser este elemento
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Cliquenosváriosli's,emaisqueumaveznomesmo<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>
PassingFunction
Althoughmuchlesscommonitisalsopossibletopassafunctionthattellsyouwhetherornotitmatchestheelement.Thematchisdonethroughwhichthefunctionreturns,andtruematchestheis
matchandfalsedoesnotmatch.Inthisfunctionyoucanimplementwhateverlogicyouwant.
Usuallythisformtakesthefollowinglook:
if($(this).is(function(){//funçãoparaavaliarseéounãoretornandoumbooleano}){//códigoparaexecutarquandoé}
Exampleofais
thatcheckswhethertheclickedelementmatchesonethathasaspecifictext:
$("li").on("click", function(){
if ($(this).is(function(){
return $(this).text() == "5";
})){
console.log("li com texto 5");
}
else {
console.log("li com texto diferente de 5");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Cliquenosváriosli's<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>
Inthiscaseyoucanalsousea Arrow Function to simplify the function code, turning it into:
If you look at the code you have in question and for my example of passing an object will see that it is the same. The code that checks whether the clicked element is different from the last one clicked:
It also saves changes if there is one last one (the first one that does not have the last one):