gpt4 book ai didi

JavaScript - 按类获取 div 中的文本

转载 作者:行者123 更新时间:2023-12-03 07:06:20 25 4
gpt4 key购买 nike

我试图使用 javascript 按类名获取 div 的内容/文本。结果不是我所期望的。我确实尝试将其插入数组,但它似乎不起作用。请帮忙!

到目前为止我做了什么:

JavaScript:

var elements = document.body.getElementsByClassName("headline-bar");

window.onload = function() {

var year= document.getElementById("year");
for (i=0;i<elements.length;i++)
{
var Entry = document.createElement("option");
Entry.text = elements[i];
year.add(Entry ,null);
}
}

HTML:

<form>
<select id="year">
</select>
</form>
<input type="submit" value="Submit">

<div class="headline-bar">2015</div>
<div class="headline-bar">2014</div>

输出:

enter image description here

期望的结果:

enter image description here

最佳答案

Use Node.textContent, The Node.textContent property represents the text content of a node and its descendants

var elements = document.body.getElementsByClassName("headline-bar");

window.onload = function() {
var year = document.getElementById("year");
for (i = 0; i < elements.length; i++) {
var Entry = document.createElement("option");
Entry.text = elements[i].textContent;
year.add(Entry, null);
}
}
<form>
<select id="year">
</select>
</form>
<input type="submit" value="Submit">

<div class="headline-bar">2015</div>
<div class="headline-bar">2014</div>

关于JavaScript - 按类获取 div 中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36807194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com