How to get multiple elements by class name that are changing?

1k Views Asked by At

Can anyone help me? I am trying to select multiple elements by class name. Everything is good until somewhere in the middle of page comments text is not available, just reviewers name and product that has been reviewed. How to set it to skip the element and move to the next row if it is not present for that particular row?

edited: So after suggestions, I tried using the below code but Console is saying
-forEach is not a function. I am running this on the following page: 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);
});
2

There are 2 best solutions below

2
Raman Dhoot On

getElementsByClassName returns all the element having the specified class, irrespective of its siblings or parent. Here you can give the some class to the row's parent class:

So as the html structure will be as follows :

<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);
});

I hope this will resolve your issue

1
Nikola Lukic On

Must be for loop not forEach. It is HTMLCollection not simple array.

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>