JavaScript 如何动态读取div中的所有span元素
在本文中,我们将学习如何读取<div>
元素中所有<span>
元素的文本内容。
方法
我们首先将选择要查找<span>
元素的div内部的分区。可以通过使用 getElementById() 方法通过其ID选择元素来实现。接下来,我们将获取包含在此分区中的指定类型的所有元素。可以通过在前一步找到的分区上使用 getElementsByTagName() 方法来实现。然后,我们可以通过循环遍历所有span元素并将其显示为列表来获取其内部的文本内容。
语法:
let getInfo = () => {
// Get the division inside which the
// spans have to be found
let container = document.getElementById("container");
let spans = container.getElementsByTagName("span");
// Get output element
let outputP = document.getElementById("output");
// Iterate over spans
for (let span of spans) {
// Create a new list element with the data
let listElem = document.createElement("li");
listElem.textContent = span.textContent;
// Insert text content of span inside output html element
outputP.appendChild(listElem);
}
};
下面的例子演示了这种方法。
示例1
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<!-- Define the span elements
with text content -->
<div id="container">
<span> Span 1 </span>
<span> Span 2 </span>
<span> Span 3 </span>
<span> Span 4 </span>
<span> Span 5 </span>
<span> Span 6 </span>
</div>
<button onclick="getInfo()" style="margin-top: 20px;">
Get Text
</button>
<h4>
Text of only <span> elements
inside division:
</h4>
<ul id="output"></ul>
<script>
let getInfo = () => {
// Get the division inside which the
// spans have to be found
let container =
document.getElementById("container");
let spans =
container.getElementsByTagName("span");
// Get output element
let outputP =
document.getElementById("output");
// Iterate over spans
for (let span of spans) {
// Create a new list element
// with the data
let listElem =
document.createElement("li");
listElem.textContent =
span.textContent;
// Insert text content of span
// inside output html element
outputP.appendChild(listElem);
}
};
</script>
</body>
输出:
示例2
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<!-- Define the span elements
with text content -->
<div id="container">
<span> Span 1 </span>
<p> This is another tag </p>
<span> Span 2 </span>
<p> This is another tag </p>
<span> Span 6 </span>
</div>
<button onclick="getInfo()" style="margin-top: 10px;">
Get Text
</button>
<h4>
Text of only <span> elements
inside division:
</h4>
<p id="output"></p>
<script>
let getInfo = () => {
// Get the division inside which the
// spans have to be found
let container =
document.getElementById("container");
let spans =
container.getElementsByTagName("span");
// Get output element
let outputP =
document.getElementById("output");
// Iterate over spans
for (let span of spans) {
// Create a new list element
// with the data
let listElem =
document.createElement("li");
listElem.textContent =
span.textContent;
// Insert text content of span
// inside output html element
outputP.appendChild(listElem);
}
};
</script>
</body>
输出: