[英]How can I get values of elements from objects through for loop in an array created from a html collection?
I have several divs with the same class name, which have many elements I need values (eg numbers) from to check equality with another values, but my approach doesn't work.我有几个具有相同类名的 div,其中有许多元素我需要从中获取值(例如数字)来检查与另一个值的相等性,但我的方法不起作用。
First, I got a html collection of all divs I want.首先,我得到了我想要的所有 div 的 html 集合。 I converted the html collection to an array, so I can iterate through it.我将 html 集合转换为数组,因此我可以遍历它。
var divCol = document.getElementsByClassName("test");
var arr = Array.prototype.slice.call( divCol );
for (var i = 0, len = arr.length; i < len; i++) {
var again=arr[i];
var pSize=again[i].getElementsByClassName("product_size").value;
alert (pSize);
[...]
}
To test what's stored in the paragraph "product_size" of the div at index i, I used an alert on pSize, but it says that pSize is undefined.为了测试索引 i 处 div 的“product_size”段落中存储的内容,我对 pSize 使用了警报,但它表示 pSize 未定义。
Assuming you have HTML similar to this:假设你有类似这样的 HTML:
<div class="test"><p class="product_size">Lorem Ipsum 1</p></div>
<div class="test"><p class="product_size">Lorem Ipsum 2</p></div>
<div class="test"><p class="product_size">Lorem Ipsum 3</p></div>
<div class="test"><p class="product_size">Lorem Ipsum 4</p></div>
You could do something like:你可以这样做:
let divCol = document.getElementsByClassName('test');
let arr = Array.prototype.slice.call(divCol);
for (let i = 0; i < arr.length; i++) {
console.log(arr[i].firstChild.textContent);
}
Targeting the first child in each div
element, which would be a paragraph, and then grabbing the textContent
of that, the paragraph text.定位每个div
元素中的第一个子元素,这将是一个段落,然后获取该textContent
,即段落文本。
Console output:控制台输出:
Lorem Ipsum 1
Lorem Ipsum 2
Lorem Ipsum 3
Lorem Ipsum 4
Get paragraph text inside an element 获取元素内的段落文本
nodeValue vs innerHTML and textContent. nodeValue 与 innerHTML 和 textContent。 How to choose? 如何选择?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.