jQuery-JavaScript: Basic Cheat Sheet for Beginners

by
on December 20, 2009
(0 minute read)

Content

Check if element exists

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

Please donate to keep this server up

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);

Simple Cloud Hosting Built for Developers

Filter words, numbers or symbols

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

Timer

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

Did you enjoy this article?

Thank with a coffee ☕

Or help me out by clicking one of these buttons:

    
    

One comment

  • Some Mike says:

    Thank you Xavi, this is great.

    I am with you on this, everyone is free to block ads, and as content creators we are free to block them. Period. I spend a lot of hours working on my blog with thousands of people every day benefiting from it and it is a shame I can’t even pay for the server expenses

Follow me for cool new products and interesting findings on graphic design, web development, marketing, startups, life and humor.


/*Twitter*/ !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); /*Facebook*/ (function(d, s, id) {var js, fjs = d.getElementsByTagName(s)[0];if (d.getElementById(id)) {return;}js = d.createElement(s); js.id = id;js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId=28624667607";fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk')); /*Google+*/ window.___gcfg = {lang: 'en-GB'};(function() {var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;po.src = 'https://apis.google.com/js/plusone.js';var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);})();
Airbnb 25€ discount