jQuery对DOM的基本操作
Manipulate DOM with jQuery
最近在CodeSchool(现在改叫Pluralsight了)稍微系统学习了一下jQuery的选择器,还有DOM操作,感觉还是挺有用的,在这边记个笔记。
1. 查找
1.1 基本选择器
$('p');
$('div#header');
1.2 子选择器
$("#destination li"); //这样会选择ul#desination下所有的<li>,但是我们只向选择他的直接子节点,而不是他的子节点的子节点
$("#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从0开始,所以这个会选择第0,2,4个li
$("#destination li:even");
1.5 Traversing
$("#destination").find("li") // $("#destination") -> selection; find("li") -> traversal; 会快一些
$("li").first() //比$("li:first")更快
1.6 Walking the DOM
$("li").first().next()
$("li").last().prev()
$("li").first().parent()
$("#destination").children("li") //children()和find()不同,children()只选择直系子节点
2.操作DOM
2.1 插入元素 (appending)
var price = $('<p>$399.99</p>') // create a node
var newOption = $('<option>', { value: 'id', text: 'name'}) // create new note with attributes
用于插入节点的话,可以使用 .append(javascript
$("div").append(<element>)
加在d iv节点内部的底部
$("div").prepend(<append>)
插入div节点内部顶部
.after(<element>) .before(<element>)
//插入当前节点相邻的前后
反之,对于被插入的元素,有对应的方法 appendTo(), prependTo(), insertAfter(), insertBefore()
2.2 移除元素
.remove()