JavaScript 如何获取DOM元素的所有ID
给定一个HTML文档,任务是将DOM元素的所有ID存储在一个数组中。有两种方法可以解决这个问题,如下所示:
方法1
- 首先使用 $(‘*’) 选择器选择所有元素,该选择器选择文档中的每个元素。
- 使用 .each()方法 遍历所有元素,并检查它是否有ID。
- 如果它有ID,则将其推入数组中。
示例: 下面的示例实现了上述方法。
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to get all ID of the DOM
elements with JavaScript ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<p>
Click on the button to get
all IDs in an array.
</p>
<button onclick="muFunc()">
Click Here
</button>
<p id="GFG"></p>
<script>
let res = document.getElementById("GFG");
function muFunc() {
let ID = [];
$("*").each(function () {
if (this.id) {
ID.push(this.id);
}
});
res.innerHTML = ID;
}
</script>
</body>
</html>
输出:

方法2
- 首先使用 $(‘*’)选择器 选择所有元素,它选择文档的每个元素。
- 使用 .map()方法遍历所有元素并检查它是否具有ID。
- 如果它有ID,然后使用 .get()方法 将其推送到数组中。
示例: 这个示例实现了上述方法。
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to get all ID of the DOM
elements with JavaScript ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<p>
Click on the button to get
all IDs in an array.
</p>
<button id="Geeks" onclick="muFunc()">
Click Here
</button>
<p id="GFG"></p>
<script>
let res = document.getElementById("GFG");
function muFunc() {
let ID = [];
ID = $("*").map(function() {
if (this.id) {
return this.id;
}
}).get();
res.innerHTML = ID;
}
</script>
</body>
</html>
输出:

极客教程