JS Check String and more

Hi all,

I am trying to do something fun. On a wooCommerce checkout page I want to see if the the item has more than one in the checkout. This is the HTML:

<td class="product-name">Product Name&nbsp;<strong class="product-quantity">× 2</strong>													</td>

and this is my JS:

let testy = document.querySelectorAll('.product-quantity');


let wordss = "x 2"

for(let i = 0; i < testy.length; i++){


and then I have tried to write it like this:

const chekys = document.getElementsByClassName('.product-quantity');    

if(chekys.firstChild.length <= 1){
	console.log('just one');	
} else {
	console.log('I need to two or more');	

and tried this:

if (chekys.firstElementChild.length <= 1){
	console.log('just one');
} else if(chekys.firstElementChild.length >= 2)(
	console.log('I need to two or more');	

I’ve got my JS books out and read but literally cannot do this…

So I am here. I was trying to do this for a bit of fun, but slowly losing my sanity. There has to be a way to either:

  • Check the string of the call .product-quantity for it being ‘x 2’ or

  • the node length being greater than 2

I’m clearly lost, please help.



Part of the problem in this code? testy.includes(wordss)testy is an HTMLElement, and as such, doesn’t have an includes() method. Instead, try checking testy[i].textContent.includes(wordss)

Next, let’s take a look at your second code sample:

Start with the first line, where you are retrieving the elements by className. Is the className .product-quantity? As a matter of fact, no. If you are using document.getElementsByClassName(), then you’d simply use the classname, without the leading dot to indicate a class.

If, on the other hand, you were to use document.querySelectorAll(), then yes, you’d use the class selector (.product-quantity) rather than simply using the classname.

Now, things get a little strange after that - when you do the getElementsByClassName(), you don’t get an array back. You get an HTMLCollection (https://devdocs.io/dom/htmlcollection), which has a few handy utilities of its own. You would still use the for loop, just as you did with the first code sample, but the accessors may change:

// alternatively, 
const chekys = document.getElementsByClassName('product-quantity');    

for (let index=0; index < chekys.length; index++){
    // here, our HTMLElement had the 'x 2' string in its text
  } else {
    // and here, it did not.

chekys just doesn’t have a firstChild or firstElementChild or whatever.

If you’d like to see the above working, take a look at this repl.

1 Like