.is () jQuery - how does it work?

2

As the function .is () works in jQuery, I've seen it being used in a code, in the code it has a $ lastClicked variable, declared, then a comparison is made (! $ (this) .is ($ lastClicked) ), only I did not understand how .is () works, and what is the purpose of the lastClicked $ in the code! if anyone can respond - thank you.

The code is as follows:

// Apenas parte do código ...
$(function(){
    var $lastClicked;
    function onTarefaItemClick(){
        if(!$(this).is($lastClicked)){
            if($lastClicked !== undefined){
                savePendingEdition($lastClicked);
            }
            $lastClicked = $(this);
            var text = $lastClicked.children('.tarefa-texto').text();
            var html = '<input type="text" class="tarefa-edit" value="' + text + '">';
            $lastClicked.html(html);
            $('.tarefa-edit').keydown(onTarefaEditKeydown);
        }
    }
    $('.tarefa-item').click(onTarefaItemClick);
    function onTarefaEditKeydown(event){
        if(event.which === 13){
            savePendingEdition($lastClicked);
            $lastClicked = undefined;
        }
    }
});
    
asked by anonymous 01.08.2018 / 18:08

3 answers

4

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:

  • Selector
  • Object
  • Function

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,andtruematchestheismatchandfalsedoesnotmatch.Inthisfunctionyoucanimplementwhateverlogicyouwant.

Usuallythisformtakesthefollowinglook:

if($(this).is(function(){//funçãoparaavaliarseéounãoretornandoumbooleano}){//códigoparaexecutarquandoé}

Exampleofaisthatcheckswhethertheclickedelementmatchesonethathasaspecifictext:

$("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 ($(this).is(() => $(this).text() == "5"){
    console.log("li com texto 5"); 
}

Code shown in question

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:

if(!$(this).is($lastClicked)){

Will do several things and save the last click as the current:

$lastClicked = $(this);

It also saves changes if there is one last one (the first one that does not have the last one):

if($lastClicked !== undefined){
    savePendingEdition($lastClicked);
    
01.08.2018 / 19:14
5

The is () function of jQuery is used to check if an object "hits" with a particular selector.

See this example:

console.log("O elemento 'i' é um input: " + $('#i').is('input'));
console.log("O elemento 'i' é um input text: " + $('#i').is('input[type=text]'));
console.log("O elemento 'i' é um input radio: " + $('#i').is('input[type=radio]'));

console.log("O elemento 'c' é um input: " + $('#c').is('input'));
console.log("O elemento 'c' é um input text: " + $('#c').is('input[type=text]'));
console.log("O elemento 'c' é um input checkbox: " + $('#c').is('input[type=checkbox]'));
console.log("O elemento 'c' é um input checkbox e está checado: " + $('#c').is('input[type=checkbox]:checked'));
console.log("O elemento 'c' é um input checkbox e não está checado: " + !$('#c').is('input[type=checkbox]:checked'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="i" type="text" />
<input id="c" type="checkbox" />

In the example, is() is used to compare the element with multiple selectors, checking if the element "hits" with each of them, if is as one of the selectors.

To clarify the question code example, the purpose is probably to know whether or not the element that was clicked is the same one that was previously clicked. Note that the variable $lastClicked is set to undefined , with $(this) , that is, some element clicked. At the beginning of the function, it checks if(!$(this).is($lastClicked)) , that is, if the element clicked ( this ) is not the last element that was previously clicked ( $lastClicked ).

    
01.08.2018 / 18:16
1

Another view is that what .is () does is check if the checked object $ ("x") matches the .is ("y") selector, returning a boolean.

In practice I usually use it only to check the states of the elements, examples:

Verify that a div is hidden:

var divEstaOculta = $("#minhDiv").is(":hidden"); 

Verify that an input is disabled:

var estaDesabilitado = $("#meuInput").is(":disabled");

Verify that a checkbox is checked:

var estaCheckado = $("#meuCheckbox").is(":checked");

But also true, when you compare with some object property, eg:

<div id="meuId" class="minhaClasse" ></div>

$("#meuId").is(".minhaClasse") // true
    
01.08.2018 / 23:47