1

I have several divs with the same class name, which have many elements I need values (e.g. numbers) from to check equality with another values, but my approach doesn't work.

First, I got a html collection of all divs I want. I converted the html collection to an array, so I can iterate through it.

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.

joieDvivre
  • 11
  • 2

1 Answers1

1

jsfiddle

Assuming you have HTML similar to this:

<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.

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. How to choose?

  • Thank you! At the end, I changed my code to `let pSize=arr[i].childNodes[15].textContent; ` and it worked perfect for me! – joieDvivre Jan 19 '19 at 12:18