對於 Web 開發者來說,獲取一個元素下的所有子元素是非常常見的需求。下面將從以下幾個方面闡述如何獲取一個元素下的所有子元素:
一、使用JavaScript的childNodes屬性
<!DOCTYPE html>
<html>
<head>
<title>獲取子元素</title>
</head>
<body>
<div id="parent">
<p>第一段文字</p>
<p>第二段文字</p>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<script>
const parent = document.getElementById('parent');
const children = parent.childNodes;
console.log(children);
</script>
</body>
</html>
childNodes 屬性返回一個 NodeList 對象,其中包含了指定元素的所有子元素。值得一提的是,NodeList 對象不僅包含 Element 元素,還包括其他類型的節點——例如 Text 節點和 Comment 節點。
二、使用JavaScript的children屬性
<!DOCTYPE html>
<html>
<head>
<title>獲取子元素</title>
</head>
<body>
<div id="parent">
<p>第一段文字</p>
<p>第二段文字</p>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<script>
const parent = document.getElementById('parent');
const children = parent.children;
console.log(children);
</script>
</body>
</html>
children 屬性返回一個 HTMLCollection 對象,其中包含了指定元素的所有子元素。與 childNodes 屬性不同的是,HTMLCollection 對象只包含 Element 元素。
三、使用JavaScript的querySelectorAll方法
<!DOCTYPE html>
<html>
<head>
<title>獲取子元素</title>
</head>
<body>
<div id="parent">
<p>第一段文字</p>
<p>第二段文字</p>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<script>
const parent = document.getElementById('parent');
const children = parent.querySelectorAll('*');
console.log(children);
</script>
</body>
</html>
querySelectorAll 方法返回一個 NodeList 對象,其中包含了符合指定 CSS 選擇器的所有元素。使用 “*” 作為選擇器,可以匹配所有元素。
四、使用jQuery的find方法
<!DOCTYPE html>
<html>
<head>
<title>獲取子元素</title>
</head>
<body>
<div id="parent">
<p>第一段文字</p>
<p>第二段文字</p>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
const parent = $('#parent');
const children = parent.find('*');
console.log(children);
</script>
</body>
</html>
jQuery 的 find 方法返回一個包含了符合指定選擇器的所有子元素的 jQuery 對象。使用 “*” 作為選擇器,可以匹配所有元素。
原創文章,作者:BRXP,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/137177.html