0

谁能帮我?我正在尝试按类名选择多个元素。一切都很好,直到页面中间的某处评论文本不可用,只有评论者姓名和已评论的产品。如果该特定行不存在该元素,如何将其设置为跳过该元素并移至下一行?

编辑:所以根据建议,我尝试使用下面的代码,但控制台说
- forEach is not a function。我在以下页面上运行它: https ://www.etsy.com/shop/FamilyshirtsCo/reviews

var productRows = document.getElementsByClassName("div.flag-body pb-xs-0");
productRows.forEach(function(productRow){
var name = productRow.querySelector(".p.shop2-review-attribution");
var comments = productRow.querySelector(".p.prose break-word m-xs-0");
var product = productRow.querySelector(".flag-body hide-xs hide-sm");
var final = product[i].innerText +" | "+ price[i].innerText +" | "+ 
quantity[i].innerText;
console.log(final);
});
4

2 回答 2

1

getElementsByClassName 返回具有指定类的所有元素,无论其兄弟姐妹或父级如何。在这里,您可以将某些类赋予行的父类:

因此html结构如下:

<div class="product-row">
    <div class="product">
        some product
    </div>
    <div class="price">
        some price
    </div>
    <div class="quantity">
        some quantity
    </div>
</div>

Javascript:

var productRows = document.getElementsByClassName("product-row");
productRows.forEach(function(productRow){
    var product = productRow.querySelector(".product");
    var price = productRow.querySelector(".price");
    var quantity = productRow.querySelector(".quantity");
    var order = product[i].innerText +" | "+ price[i].innerText +" | "+ quantity[i].innerText;
    console.log(order);
});

我希望这能解决你的问题

于 2020-02-14T10:46:28.797 回答
0

必须是 for 循环而不是 forEach。它是 HTMLCollection 不是简单的数组。

var productRows = document.getElementsByClassName("product-row");

for ( var x = 0; x < productRows.lenght; x++) {
 var product = productRows[x].querySelector(".product");
 var price = productRows[x].querySelector(".price");
 var quantity = productRows[x].querySelector(".quantity");
 var order = product[i].innerText + " | " +
   price[i].innerText + " | " +
   quantity[i].innerText;
   
 console.log(order);
};
 <div class="product-row">
        <div class="product">
            some product
        </div>
        <div class="price">
            some price
        </div>
        <div class="quantity">
            some quantity
        </div>
    </div>

于 2020-02-14T10:58:37.653 回答