- jQuery 教程
- jQuery - 首頁
- jQuery - 路線圖
- jQuery - 概述
- jQuery - 基礎
- jQuery - 語法
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 屬性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 新增元素
- jQuery - 刪除元素
- jQuery - 替換元素
- jQuery CSS 操作
- jQuery - CSS 類
- jQuery - 尺寸
- jQuery - CSS 屬性
- jQuery 效果
- jQuery - 效果
- jQuery - 動畫
- jQuery - 鏈式呼叫
- jQuery - 回撥函式
- jQuery 遍歷
- jQuery - 遍歷
- jQuery - 遍歷祖先節點
- jQuery - 遍歷後代節點
- jQuery UI
- jQuery - 互動
- jQuery - 小部件
- jQuery - 主題
- jQuery 參考
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍歷
- jQuery - 雜項
- jQuery - 屬性
- jQuery - 實用程式
- jQuery 外掛
- jQuery - 外掛
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用資源
- jQuery - 問答
- jQuery - 快速指南
- jQuery - 有用資源
- jQuery - 討論
jQuery children() 方法
jQuery 中的 children() 方法用於選擇所選元素的所有直接子元素。它向下遍歷 DOM 樹以查詢作為所選元素的直接後代的子元素。它不會遍歷所有後代,僅遍歷直接子元素。
注意:如果我們想要深入遍歷並返回孫子或其他後代,我們需要使用 find() 方法。
語法
以下是 jQuery 中 children() 方法的語法:
$(selector).children(filter)
引數
此方法接受以下可選引數:
- filter: 包含用於篩選子元素的選擇器表示式的字串。
示例 1
在以下示例中,我們使用 children() 方法返回 <ul> 的直接子元素:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("ul").children().css("color", "#40a944");
});
</script>
</head>
<body>
<ul>Parent
<li>children 1</li>
<li>children 2</li>
<li>children 3</li>
<li>children 4</li>
</ul>
</body>
</html>
當我們執行上述程式時,children() 方法將返回 <ul> 元素下的所有元素,並將它們的顏色更改為綠色。
示例 2
在這裡,我們選擇所有類為 'one' 的 li 元素,這些元素是其父 ul 元素的直接子元素:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("ul").children(".one").css("color", "#40a944");
});
</script>
</head>
<body>
<ul>Parent
<li>child 1</li>
<li class="one">child 2</li>
<li class="one">child 3</li>
<li class="second">child 4</li>
</ul>
</body>
</html>
執行上述程式後,類為 'one' 的 li 元素將被返回,並且文字顏色為綠色。
示例 3
在下面的示例中,我們選擇所有作為其父 div 元素的直接子元素的 span 元素:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("div").children("p").css("color", "#40a944");
});
</script>
</head>
<body>
<div>Parent
<p>paragraph: child</p>
<span>span: child</span>
<p>paragraph: child</p>
<span>span: child</span>
<p>paragraph: child</p>
</div>
</body>
</html>
當我們執行上述程式時,children() 方法將返回所有作為 div 的直接子元素的 span 元素,並將它們的顏色更改為綠色。
jquery_ref_traversing.htm
廣告
