Skip to content

Instantly share code, notes, and snippets.

View UltCombo's full-sized avatar

Fabricio Matte UltCombo

View GitHub Profile
$('html').appendTo('body');
//para testar se nosso objeto jQuery possui elementos:
if ($el.length) {/*...*/}
//isto é equivalente à:
if ($el.length !== 0) {/*...*/}
//Já que .length sempre é um número >= 0, também podemos escrever:
if ($el.length > 0) {/*...*/}
//e para ver se não possui nenhum elemento:
if (!$el.length) {/*...*/}
//isto equivale à:
var $el = $('#precisaExistir');
//realizamos testes primeiro
if (!$el.length) {
throw '#precisaExistir não encontrado.';
}
//passou pelos testes básicos, executamos a funcionalidade da função/script
$el.css('backgroundColor', 'green');
var $el = $('#precisaExistir');
if ($el.length) {
$el.css('backgroundColor', 'green');
} else {
throw '#precisaExistir não encontrado.';
}
var $el = $('#precisaExistir');
if ($el.length) {
$el.css('backgroundColor', 'green');
} else {
alert('Deu pau aqui tio.');
}
console.log( $('#precisaExistir').length );
//com jQuery
$('#talvezExista').css('backgroundColor', 'green');
//JS nativo
var el = document.getElementById('talvezExista');
if (el) {
el.style.backgroundColor = 'green';
}
$('#IDinexistente').css('backgroundColor', 'green');
document.getElementById('IDinexistente').style.backgroundColor = 'green';
>>> [1, 2].toString()
<<< "1,2"
>>> [1, 2] == '1,2'
<<< true
>>> +''
<<< 0