jQuery-JavaScript: Basic Cheat Sheet for Beginners

20 Dec 2009

Content

Check if element exists

if ($('#infobox').length) { /*exists, do things here*/ }

Change attribute

$('#name').attr('title', 'Hello!');

Change content of a container

$('#main').html('<p>Lorem ipsum</p>');

Change page title

document.title = 'Hello!';

Add content before/after

$('table>tbody>tr:last').after('<tr><td>This is now the last row.</td></tr>');

Style

Add or remove classes

$('#main').addClass('red');
$('#main').removeClass('blue');

Check if element has class

if ($('#main').hasClass('green')) { }

Ajax

GET with parameters

$.get("page.php", { action: "edit", id: 38 },
  function(data){
   $('#infobox').html(data);
});

Loops

Do something with every matching element

$('table>tbody>tr').each(
  function (intIndex) {
    /* Modify all table rows */
});

Maths

Check if even or odd

if ($id % 2) { /*even*/ }else{ /*odd*/ }

Force string to integer

parseInt(var);

Filter words, numbers or symbols

$(this).attr('id').replace(/[^0-9]+/, '');

Timer

setInterval(timer1s, 1000);
function timer1s() { /*run this every second*/ }
               
       

Comments

1 comment to jQuery-JavaScript: Basic Cheat Sheet for Beginners

Comment Form