1. Selecionar elementos
jQuery:
o jQuery()
função, ou $()
resumindo, é a função global no jQuery que você pode usar para selecionar qualquer elemento no DOM.
/* Syntax */ jQuery(); $(); // shortcut
/** * Example * * Selects all the links among the descendants of the 'my-class' class */ jQuery('.my-class a'); $('.my-class a');
Veja mais nos documentos da API jQuery: função global jQuery().
JavaScript:
/* Syntax */ Document.querySelectorAll();
/* Example */ document.querySelectorAll('.my-class a');
Veja mais na documentação da API DOM: método .querySelectorAll().
2. Selecione o primeiro elemento
jQuery:
/* Syntax */ .first();
/** * Example * * Selects the first link among the descendants of the 'my-class' class */ $('.my-class a').first();
Veja mais na documentação da API do jQuery: método first().
JavaScript:
/* Syntax */ Document.querySelector();
/* Example */ document.querySelector('.my-class a');
Veja mais na documentação da API DOM: método .querySelector().
3. Encontrar elementos
jQuery:
/* Syntax */ .find();
/** * Example * * Find all the span tags that are descendants of links within * the 'my-class' class * * Note: searches for all descendants not just for children */ $('.my-class a').find('span'); $('.my-class a').find('span').css('color', 'red'); // for testing
Veja mais na documentação da API do jQuery: Método .find().
JavaScript:
/* Syntax */ // to find the first element (also if there's only one) Document.querySelector(); // to find all elements Document.querySelectorAll();
/** * Example * * At first querySelectorAll() returns a NodeList, so we have to loop * through it to find all the span tags we want * * For the sake of testing, I made the selected elements red, * you can find the 'style.color' property below in this cheat sheet */ // finds all '.my-class a' let nodes = document.querySelectorAll('.my-class a'); // loops through all '.my-class a' for (let i = 0; i < nodes.length; i++) { // checks if the individual '.my-class a' element has a // 'span' descendant to avoid 'undefined' error if (nodes[i].querySelector('span')) { // colors span tags that are desdendants of '.my-class a' nodes[i].querySelector('span').style.color="red"; } }
Veja a demonstração do código:
Veja mais nos documentos da API DOM: método .querySelector(), método .querySelectorAll().
4. Selecionar filhos
jQuery:
/* Syntax */ .children(); .children('selector');
/** * Example * * (1) Finds all the children of all '.my-class a' elements on the age * * (2) Finds all the 'span' elements that are the children of * any '.my-class a' element on the page * * Note: searches only for children (first-level of descendants) */ $('.my-class a').children(); $('.my-class a').children('span'); $('.my-class a').children('span').css('color', 'blue'); // for testing
Veja mais na documentação da API do jQuery: método .children().
JavaScript:
/* Syntax */ ParentNode.children;
/** * Example * * 2nd example of the jQuery version above, plus makes the selected span * tags blue for the sake of easy testing * * for 1st example, only leave out the if check at the end (we need this * because the JS version is not a method but a property, so we * need to check which children are 'span') * */ // selects all the elements with 'my-class a' on the page let items = document.querySelectorAll('.my-class a'); // loops through all the elements with '.my-class a' for (let i = 0; i < items.length; i++) { // finds the children of the current '.my-class a' element let kids = items[i].children; // loops through the children of the current '.my-class a' element for (let j = 0; j < kids.length; j++) { // checks if the child element is a span tag if (kids[j].tagName == 'SPAN') { kids[j].style.color="blue"; } } }
Veja o código de teste:
Veja mais na documentação da API DOM: Propriedade .children – lembre-se que enquanto a versão JavaScript é uma propriedade, a versão jQuery era um método com um parêntese depois.
5. Selecionar pai
jQuery:
/* Syntax */ .parent();
/** * Example * * Selects the parent elements of ALL elements with 'my-class a' * on the page */ $('.my-class a');
Veja mais nos documentos da API do jQuery: método .parent()
JavaScript:
/* Syntax */ Node.parentNode;
/** * Example * * Selects the parent of the FIRST element with 'my-class a' on the page * (for the sake of less repetition) * * For looping through all '.my-class a' elements, use the looping * solution and querySelectorAll() from the two examples above. */ let item = document.querySelector('.my-class a'); item.parentNode;
Veja mais nos documentos da API DOM: propriedade .parentNode.
6. Selecionar irmãos
jQuery:
/* Syntax */ .siblings();
/** * Example * * Selects the siblings of ALL elements with the 'find-siblings' * class on the page */ $('.find-siblings').siblings();
Veja mais na documentação da API do jQuery: método .siblings().
JavaScript:
/* Syntax */ Node.parentNode.querySelectorAll(":not(#elem)");
/** * Example * * Selects the siblings of the FIRST element with the * 'find-siblings' class * * For looping through all 'find-siblings' elements, see examples #3 and #4 * * the ':scope' pseudoclass is necessary for preventing the child * elements of 'item' from being selected (otherwise querySelectorAll() * searches through all descendants of 'item', with ':scope >' it loops * through just the first level) * */ let item = document.querySelector('.find-siblings'); let siblings = item.parentNode.querySelectorAll(':scope > :not(.find-siblings)');
Veja demonstração de teste:
Veja mais na documentação da API DOM: propriedade .parentNode, método .querySelectorAll(), pseudoclasse :scope (consulte a seção 'Filhos diretos').
7. Selecione o próximo irmão
jQuery:
/* Syntax */ .next();
/** * Example * * Selects the next siblings of all elements with 'my-class a' * on the page */ $('.my-class a').next();
Veja mais na documentação da API do jQuery: Método .next().
JavaScript:
/* Syntax */ NonDocumentTypeChildNode.nextElementSibling;
/** * Example * * For declaring the 'item' variable by selecting elements with * 'my-class a' on the page, see examples #3, #4, #5 */ item.nextElementSibling;
Veja mais nos documentos da API DOM: propriedade .nextElementSibling.
8. Selecionar irmão anterior
jQuery:
/* Syntax */ .prev();
/** * Example * * Selects the previous siblings of all elements with 'my-class a' * on the page */ $('.my-class a').prev();
Veja mais na documentação da API do jQuery: Método .prev().
JavaScript:
/* Syntax */ NonDocumentTypeChildNode.previousElementSibling;
/** * Example * * For declaring the 'item' variable by selecting elements with * 'my-class a' on the page, see examples examples #3, #4, #5 */ item.previousElementSibling;
Veja mais nos documentos da API DOM: propriedade .previousElementSibling.
9. Encontre o elemento de correspondência mais próximo
jQuery:
/* Syntax */ .closest('selector-name');
/** * Example * * Checks each 'my-class' element and all of its parent elements, * then returns the first paragraph element it finds. */ $('.my-class').closest('p');
Veja mais na documentação da API do jQuery: método .closest().
JavaScript:
/* Syntax */ Element.closest();
/** Example * * Checks item and all of its parents and returns the first div it finds * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.closest('div');
Veja demonstração de teste:
Veja mais na documentação da API DOM: método .closest().
10. Adicionar turma
jQuery:
/* Syntax */ .addClass();
/** * Example * * Adds the 'second-class' class to every 'my-class' element * */ $('.my-class').addClass('second-class');
Veja mais nos documentos da API do jQuery: Método .addClass().
JavaScript:
/* Syntax */ Element.classList.add();
/** * Example * * For declaring the 'item' variable by selecting elements with 'my-class' * on the page, see examples examples #3, #4, #5 */ item.classList.add('second-class');
Veja mais nos documentos da API DOM: propriedade .classList e método .add().
11. Remover classe
jQuery:
/* Syntax */ .removeClass();
/** * Example * * (1) Removes the 'second-class' class from every 'my-class' element * * (2) Removes 'second-class', then add 'third-class' to * every 'my-class' element */ $('.my-class').removeClass('second-class'); $('.my-class').removeClass('second-class').addClass('third-class');
Veja mais na documentação da API do jQuery: Método .removeClass().
JavaScript:
/* Syntax */ Element.classList.remove();
/** * Example * * For declaring the 'item' variable by selecting elements with 'my-class' * on the page, see examples examples #3, #4, #5 */ item.classList.remove('second-class'); // To use it together with add(), you need two separate statements item.classList.remove('second-class'); item.classList.add('third-class');
Veja mais na documentação da API DOM: propriedade .classList, método .remove().
12. Alternar classe
jQuery:
/* Syntax */ .toggleClass();
/** Example * * Adds the 'active' class to elements with 'my-class' if they don' have it * remove it if they have it * */ $('.my-class').toggleClass('active');
Veja mais na documentação da API do jQuery: método .toggleClass().
JavaScript:
/* Syntax */ Element.classList.toggle();
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.classList.toggle('active');
Veja mais na documentação da API DOM: propriedade .classList, método .toggle().
13. Tem classe
jQuery:
/* Syntax */ .hasClass();
/** * Example * * Checks if any element with 'my-class' has the 'active' class * * Returns true or false * * If there's at least one element with 'active' it's true, * otherwise false. * */ $('.my-class').hasClass('active');
Veja mais na documentação da API do jQuery: Método .hasClass().
JavaScript:
/* Syntax */ Element.classList.contains();
/** * Example * * Similar to the jQuery version, this one also checks if any element * in the whole classList has the 'active' class * * If at least one element has 'active', it's true, otherwise false * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.classList.contains('active');
Veja mais na documentação da API DOM: propriedade .classList, método .contains().
14. Obter atributo
jQuery:
/* Syntax */ .attr('attr-name');
/** * Example * * Returns the value of the href property of the FIRST occurrence of * an element with 'my-class' * */ $('.my-class').attr('href');
Veja mais na documentação da API do jQuery: método .attr().
JavaScript:
/* Syntax */ Element.getAttribute('attr-name');
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.getAttribute('href');
Veja mais na documentação da API DOM: método .getAttribute().
15. Definir atributo
jQuery:
/* Syntax */ .attr('attr-name', value);
/** * Example * * Sets the value of the href property for ALL contact links that * have the 'contact-link' class * */ $('.contact-link').attr('href', 'contact.html');
Veja mais na documentação da API jQuery: método .attr() (você precisa usar o mesmo .attr()
método para obter um valor de atributo, mas com dois parâmetros em vez de um).
JavaScript:
/* Syntax */ Element.setAttribute();
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.setAttribute('href', 'contact.html');
Veja mais na documentação da API DOM: método .setAttribute().
16. Remover atributo
jQuery:
/* Syntax */ .removeAttr('attr-name');
/** * Example * * Removes 'target' attributes from contact links */ $('.contact-link').removeAttr('target');
Veja mais na documentação da API do jQuery: método .removeAttr().
JavaScript:
/* Syntax */ Element.removeAttribute();
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.removeAttribute('target');
Veja mais na documentação da API DOM: método .removeAttribute().
17. Anexar um novo elemento filho
jQuery:
/* Syntax */ .append('html-string');
/** * Example * * Appends an extra list element to the end of every ordered list on the page * */ $("ol").append("
Veja mais nos documentos da API do jQuery: método .append().
JavaScript:
/* Syntax */ Node.appendChild();
/** * Example * * For declaring the 'ol' variable, see examples #3, #4, #5 */ ol.appendChild(document.createElement("li"));
Veja mais nos documentos da API DOM: método .appendChild() e método .createElement().
18. Anexar um novo elemento filho
jQuery:
/* Syntax */ .prepend('html-string');
/** * Example * * Prepends an extra list element to the beginning of every ordered list on the page * */ $("ol").prepend("
Veja mais na documentação da API do jQuery: método .prepend().
JavaScript:
/* Syntax */ Node.insertBefore();
/** * Example * * For declaring the 'ol' variable, see examples #3, #4, #5 */ ol.insertBefore(document.createElement("li"), ol.firstChild);
Veja o código de teste (para anexar e preceder um nó filho):
Veja mais nos documentos da API DOM: método .insertBefore(), método .createElement() e propriedade firstChild.
19. Remover todos os nós filhos
jQuery:
/* Syntax */ .empty();
/** * Example * * Removes all child nodes (HTML + text) of each element * that has 'my-class' */ $('.my-class').empty();
Veja mais na documentação da API do jQuery: método .empty().
JavaScript:
/* Syntax */ Element.replaceChildren();
/** * Example * * Empties the 'item' node of all of its children * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.replaceChildren();
Veja mais na documentação da API DOM: método .replaceChildren().
20. Obter ou definir conteúdo HTML
jQuery:
/* Syntax */ .html(); .html('html-string');
/** * Example * * (1) Gets the HTML content of the FIRST element that matches 'my-class' * * (2) Sets/resets the HTML content of EACH element that matches 'my-class' * */ $('.my-class').html(); $('.my-class').html('Hello');
Veja mais nos documentos da API do jQuery: método .html().
JavaScript:
/* Syntax */ Element.innerHTML;
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.innerHTML; // gets the value item.innerHTML = 'Hello'; // sets the value
Veja mais nos documentos da API DOM: propriedade .innerHTML.
21. Substituir um elemento por novo conteúdo HTML
jQuery:
/* Syntax */ .replaceWith('new-html-content');
/** * Example * * * Selects a heading, then replaces the full HTML content, * including the parent element */ $('#my-heading').replaceWith('New Heading
');
Veja mais nos documentos da API do jQuery: método .replaceWith().
JavaScript:
/* Syntax */ Element.outerHTML = 'new HTML content';
/** * Example * * Replaces the full HTML content, including the parent element * */ let item = document.querySelector('#my-heading'); item.outerHTML = 'New Subheading
';
Veja mais nos documentos da API DOM: propriedade .outerHTML.
22. Obter ou definir propriedade CSS
jQuery:
/* Syntax */ .css('property-name'); .css('property-name', value);
/** * Example * * (1) Gets the 'color' value of the FIRST element * that has 'my-class' * * (2) Sets the 'color' value to 'white' for EVERY element that has * 'my-class' */ $('.my-class').css('color'); $('.my-class').css('color', 'white');
Veja mais nos documentos da API do jQuery: método .css().
JavaScript:
/* Syntax */ ElementCSSInlineStyle.style.{propertyName};
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.style.color; // getting value item.style.color="white"; // setting value
Veja mais nos documentos da API DOM: propriedade .style e Referência de propriedades CSS (para os nomes JavaScript das propriedades CSS).
23. Obter ou definir o conteúdo de texto de um elemento e todos os seus descendentes
jQuery:
/* Syntax */ .text(); .text('text');
/** * Example * * (1) Gets the text content of the FIRST element (and all of its descendants) that matches 'my-class' * * (2) Sets/resets the text content of EACH element that matches 'my-class' * */ $('.my-class').text(); $('.my-class').text('Hello');
Veja mais na documentação da API do jQuery: método .text().
JavaScript:
/* Syntax */ Element.textContent;
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.textContent; // gets the value item.textContent="Hello"; // sets the value
Veja mais nos documentos da API DOM: propriedade .textContent.
24. Obter ou definir valores de entrada
jQuery:
/* Syntax */ .val(); .val(val);
/** * Example * * (1) Gets the value of the input with the 'name' name * * (2) Sets/resets the value of the input with the 'name' name * */ $('input[name=name]').val(); $('input[name=name]').val('Marilyn Monroe');
Veja mais na documentação da API do jQuery: método .val().
JavaScript:
/* Syntax */ HTMLInputElement.value;
/** * Example * * For declaring the 'input' variable, see examples #3, #4, #5 */ input.value; // gets the value input.value="Marilyn Monroe"; // sets the value
Veja mais na documentação da API DOM: propriedade .value (na lista de ''Propriedades que se aplicam a qualquer tipo de elemento de entrada que não esteja oculto").
25. Ocultar elemento
jQuery:
/* Syntax */ .hide();
/** * Example * * Hides all elements with 'my-class' */ $('.my-class').hide();
Veja mais na documentação da API do jQuery: método .hide().
JavaScript:
/* Syntax */ ElementCSSInlineStyle.style.display = 'none';
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.style.display = 'none';
Veja mais nos documentos da API DOM: propriedade .style.
26. Mostrar elemento
jQuery:
/* Syntax */ .show();
/** * Example * * Displays all elements with 'my-class' */ $('.my-class').show()
Veja mais na documentação da API do jQuery: método .show().
JavaScript:
/* Syntax */ ElementCSSInlineStyle.style.display = '';
/** * Example * * For declaring the 'item' variable, see examples #3, #4, #5 */ item.style.display = ''; // resets default item.style.display = 'block'; // sets display as block item.style.display = 'flex'; // sets display as flex
Veja mais nos documentos da API DOM: propriedade .style.
27. Adicionar ouvinte de eventos
jQuery:
/* Syntax */ .on();
/** * Example * * Adds or removes the 'active' class to/from all elements with * '.submenu' when #toggle is clicked */ $('#toggle').on('click', function(){ $('.submenu').toggleClass('active'); });
Veja mais nos documentos da API do jQuery: método .on()
JavaScript:
/* Syntax */ EventTarget.addEventListener('event', functionName);
/** * Example * * The code below only selects the FIRST element with the * 'submenu' class. * * To select all submenus, use the 'for' loop in Example #3 and #4 */ let toggle = document.querySelector("#toggle"); let submenu = document.querySelector(".submenu"); toggle.addEventListener('click', function() { submenu.classList.toggle('active'); });
Veja o código de teste:
Veja mais nos documentos da API DOM: método .addEventListener() e Referência de eventos DOM.
28. Remover ouvinte de eventos
jQuery:
/* Syntax */ .off();
/** * Example * * Removes the listed event handler when #toggle is clicked */ $('#toggle').off('click', function(){ $('.submenu').toggleClass('active'); });
Veja mais na documentação da API do jQuery: método .off().
JavaScript:
/* Syntax */ EventTarget.removeEventListener('event', functionName);
/** * Example * * The code below only selects the FIRST element with the * 'submenu' class. * * To select all submenus, use the 'for' loop in Example #3 and #4 */ let toggle = document.querySelector("#toggle"); let submenu = document.querySelector(".submenu"); toggle.removeEventListener('click', function() { submenu.classList.toggle('active'); });
Veja mais nos documentos da API DOM: método .removeEventListener() e Referência de eventos DOM.
29. Executar uma função quando o DOM estiver pronto
jQuery:
/** * Syntax * * This is the jQuery 3 version of $(document).ready(function(){}); * which is now deprecated. */ $(function() { // event handler });
/** * Example * * Event: The DOM (document) is fully loaded * * Action triggered by this event: Message in the console */ $(function() { console.log('The DOM is ready!'); });
Veja mais na documentação da API do jQuery: método .ready().
JavaScript:
/* Syntax version 01 */ if(document.readyState === 'complete' || (document.readyState !== 'loading')) { // event handler } else { document.addEventListener('DOMContentLoaded', function() { // event handler }); } /** * Syntax version 02 - you can store the event handler * in a custom callback function */ let handler() = function(){ // event handler }; if(document.readyState === 'complete' || (document.readyState !== 'loading')) { handler() } else { document.addEventListener('DOMContentLoaded', handler); }
/** Example * * When the document is fully loaded, a message is logged to the console. */ // version 01 if(document.readyState === 'complete' || (document.readyState !== 'loading')) { console.log('The DOM is ready!'); } else { document.addEventListener('DOMContentLoaded', function() { console.log('The DOM is ready!'); }); } // version 02 // (with a custom 'logMessage' function that holds the event handler) let logMessage = function(){ console.log('The DOM is ready!'); }; if(document.readyState === 'complete' || (document.readyState !== 'loading')) { logMessage(); } else { document.addEventListener('DOMContentLoaded', logMessage); }
Veja mais na documentação da API DOM: propriedade readyState, método addEventListener().
30. Percorrer um objeto, array ou coleção
jQuery:
/* Syntax */ .each();
/** * Example * * Finds each paragraph and turns them yellow */ $('p').each(function() { $(this).css('color', '#fbdf00'); });
Veja mais na documentação da API do jQuery: método .each().
JavaScript:
/* Syntax */ NodeList.prototype.forEach(); // we'll use this in the example below Array.prototype.forEach(); Map.prototype.forEach(); Set.prototype.forEach();
/** * Example * * v1 turns red all paragraphs on the page * * v2 turns green all list items on the page */ // v1 (inline callback function syntax) let itemsV1 = document.querySelectorAll('p'); itemsV1.forEach( function(item) { item.style.color="white"; } ); // v2 (arrow function syntax) let itemsV2 = document.querySelectorAll('li'); itemsV2.forEach(item => item.style.color="#fbdf00");
Veja demonstração de teste:
Veja mais nos documentos da API DOM: métodos .foreach() das interfaces NodeList, Array, Map e Set.
Próximos passos
Esta folha de dicas de jQuery para JavaScript inclui as funcionalidades mais importantes que você precisará para construir um site. Ao se familiarizar com essas propriedades e métodos, você pode pular do jQuery para o JavaScript. No entanto, você provavelmente precisará saber mais se quiser criar funcionalidades mais complexas.
Há dois outros recursos que eu recomendaria para encontrar o equivalente de jQuery para JavaScript que você precisa: o site You Might Not Need jQuery e o repositório jQuery-to-JavaScript de Jack O'Connor no GitHub.
Apesar de ter usado o clássico for
loop para percorrer querySelectorAll()
correspondências, o JavaScript moderno também oferece outras opções — Chris Coyier mostra algumas delas neste artigo sobre loops de JavaScript.
Experimentar e criar seus próprios snippets de código também pode ajudar muito se você quiser usar JavaScript nativo e a API DOM com confiança em seu fluxo de trabalho diário.
Saiba mais JavaScript com Tuts+
Se você está apenas começando com JavaScript, esses tutoriais, guias e cursos do Tuts+ o colocarão na direção certa:
Originally posted 2022-08-09 14:01:45.