The hydra-universe twisting its body scaled in stars.

Manipulate DOM with jQuery


I have been using jQuery in my projects since two or three years ago, but I have never studied it carefully, basically searching the web and copying and pasting other people's code. Recently, I learned a little bit about jQuery's selectors and DOM operations at CodeSchool (which has since been renamed Pluralsight), and I think it's pretty useful to take notes here. jQuery provides a rich variety of selectors: basic selectors, subselectors, and CSS-like pseudo-class selectors, all of which are very useful. I also learned recently about the concept of Traversing, which affects the efficiency of selectors.

Here's my study note on manipulating DOM with jQuery.

1. Lookup

1.1 Basic selectors


1.2 Subselectors

$("#destination li"); // this will select all <li> under ul#desination, including the children of its children
$("#destination > li"); // select the only direct children

1.3 Mutiple Selector

$(".promo, .france");

1.4 CSS-like pseudo-classes

$("#destination li:first");
$("#destination li:last");
$("#destination li:odd"); // index starts at 0, so this will select the 0th,2nd,4th <li>
$("#destination li:even");

1.5 Traversing

$("#destination").find("li") // $("#destination") -> selection; find("li") -> traversal; faster
$("li").first() // faster than $("li:first")

1.6 Walking the DOM

$("#destination").children("li") //children() is different from find() in that children() only selects direct children

2. Manipulating the DOM

2.1 Inserting elements (appending)

var price = $('<p>$399.99</p>') // create a node
var newOption = $('<option>', { value: 'id', text: 'name'}) // create new note with attributes

For inserting nodes, you can use .append() .prepend() .after() .before()

Append to the bottom of the inner d iv node
Insert at the top of the inner div node
.after(<element>) .before(<element>)
//insert before and after the current node adjacent to it

Conversely, for the inserted element, there are corresponding methods appendTo(), prependTo(), insertAfter(), insertBefore()

2.2 Removing elements

< Back