Useful jQuery snippets

Manipulating the DOM

To manipulate the DOM by accessing its elements, use the methods listed at http://api.jquery.com/category/manipulation/. Here’s a couple of examples

// set text of element
$("#title").text("Changed!");
// set HTML of the element
$("#title").html("<i>New HTML</i>");
// remove the element from the DOM
$("#second").remove();

Dynamically applying CSS

To use jQuery to apply css classes to DOM elements dynamically, first make put the following in a .css file.

.highlight {
background-color: yellow;
}

Then do this in the .js file to apply the class to a given element with id "someElem"

$("#someElem").addClass('highlight');

This will apply the styling of the highlight css class to the element with id "someElem"

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s