1. children()方法:
该方法用于取得匹配元素的子元素集合。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="jQuery/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var $body=$("body").children();
var $p=$("p").children();
var $ul=$("ul").children();
alert($body.length);
alert($p.length);
alert($ul.length);
for(var i=0,len=$ul.length;i<len;i++){
alert($ul[i].innerHTML);
}
});
</script>
</head>
<body>
<p></p>
<ul>
<li>java</li>
<li>python</li>
<li>c++</li>
</ul>
</body>
</html>
2. next()方法:
该方法用于取得匹配元素后面紧邻的同辈元素。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="jQuery/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var $p_next=$("p").next();
alert($p_next.html());
});
</script>
</head>
<body>
<p></p>
<ul>
<li>java</li>
<li>python</li>
<li>c++</li>
</ul>
</body>
</html>
3. prev()方法:
该方法用于取得匹配元素前面紧邻的同辈元素。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="jQuery/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var $ul_prev=$("ul").prev();
alert($ul_prev.text());
});
</script>
</head>
<body>
<p>我是一个段落</p>
<ul>
<li>java</li>
<li>python</li>
<li>c++</li>
</ul>
</body>
</html>
4. siblings()方法:
该方法用于取得匹配元素前后所有的同辈元素。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
.c1{
color:red;
font-weight:bold
}
</style>
<script src="jQuery/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").click(function(){
$("#d2").siblings().removeClass("c1");
});
});
</script>
</head>
<body>
<p class="c1">我是第一段</p>
<p class="c1" id="d2">我是第二段</p>
<p class="c1">我是第三段</p>
<input type="button" value="测试siblings()方法">
</body>
</html>
访问这个页面:
单击按钮后页面变为:
除此之外,jQuery还有很多遍历节点的方法,例如closest(),find(),filter(),nextAll(),prevAll(),parent()和parents()等