The jQuery and Javascript code snippets you should learn by heart

While jQuery is a great improvement on classic Javascript, it’s still not perfect. What works in version 1.3 doesn’t automatically work in 1.7 and what works in Firefox, doesn’t automatically work in IEx. The syntax isn’t very straightforward and some properties are misleading (eg: .val() vs .value())

This is an updated! incomplete list of stuff I need regularly that works in jQuery/javascript:

DOM Hierarchy

Get an ancestor


Get a descendant


Get a sibling


Wait until the DOM-tree is complete (or “page” is loaded)



Manipulating DOM tree

Insert something after a certain element


Insert something right before the closing tag of an element




Insert something right after the opening tag of an element





Check if an element is visible

if($('#element').is(':visible')) {


Check if a checkbox is checked


Check a checkbox

$("#checkbox").attr("checked", "checked");

Difference is that you set the “checked” attribute in this example. In the previous example you get the “checked” attribute.

Uncheck a checkbox


Catch the event of (un)checking a checkbox

// do stuff here

Other form-elements

Get the value of a select form element


Catch the event of clicking a button

// do stuff here

Make sure the textbox is of type “button” and not of type “submit”.


Declaring an array

var x = [];
var y = [ 1, 2, 3 ];

Looping through an array.

for (var i = 0; i < a.length; i++) { // a[i] is your value }


Declaring an object

var x = {};
var y = {
name: "Robin",
age: 29

Get/set a property of the object

y.age += 1; //add one


Yes/no - dialog

confirm("Do you really want this subscription?");

Isn't jquery, but handy. Returns a boolean.

Ajax with POST-method

type: "POST",
url: "/theurl",
data: { text: textYouWantToSubmit},
success: function( returnHtml ) {

error: function(jqXHR, textStatus, errorThrown){

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.