How can I filter the value of a HTMLCollection

3

I'm doing a type of shopping cart, creating a list of products, through javascript, up there all right, now when I click on some product I will return an HTMLCollection in the form of an array, since there is 9 products I have HTMLCollection (9)

let prod = document.getElementsByClassName('product')

for(let i = 0;i < prod.length;i++){
  prod[i].addEventListener('click', function(){
    console.log(prod[i])
  })
}

in the prod [i] returns a product with this structure

<div class="product">
      <p class="title">Producto 1</p>
      <div class="icon"></div>
      <p class="price">$ 100</p>
    </div>

Now what I can not do is get only the name that would be 'Product 1' and the price that would be '100'

to later place it in a table.

I hope someone can help me or tell me some other way to get what I want. Thank you very much in advance: D

    
asked by david ponce 27.06.2018 в 01:10
source

1 answer

0

With jQuery it would be easier. but with vanilla javascript it would be like this:

let prod = document.getElementsByClassName('product')

for(let i = 0;i < prod.length;i++){
  prod[i].addEventListener('click', function(){
    
    let pro = prod[i].firstChild.nextElementSibling;
    let price = pro.nextElementSibling.nextElementSibling;
    
    console.log("Producto: " + pro.innerHTML + "  Precio: " + price.innerHTML);
  })
}
<div class="product">
      <p class="title">Producto 1</p>
      <div class="icon"></div>
      <p class="price">$ 100</p>
    </div>
    <div class="product">
      <p class="title">Producto 2</p>
      <div class="icon"></div>
      <p class="price">$ 1002</p>
    </div>
    <div class="product">
      <p class="title">Producto 3</p>
      <div class="icon"></div>
      <p class="price">$ 500</p>
    </div>
    
answered by 27.06.2018 / 01:30
source