Simple javascript loop not working

I am not so experienced with JavaScript yet, so Im probably didn’t notice something here:

var products = document.getElementsByClassName('product');
var productsLength = products.length;

for(var i = 0; i < productsLength; i++){
  var productGender = products[i].attr('data-gender');

  if(productGender === triggerVal){
    console.log('yes');
  } else {
    console.log('no');
  }
};

It says: products[i].attrnot a function

Should I have access to it correctly? The product is only a list item.

Thanks!

+4
source share
4 answers

attr is a jQuery method, use getAttribute

http://www.w3schools.com/jsref/met_element_getattribute.asp

+4
source
 var productGender = products[i].getAttribute('data-gender');

This is what you need, you used jquerys.attr ()

+3
source

data-xyz .dataset object

.

var productGender = products[i].dataset.gender;

MDN - https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

- IE11 + ( ) - polyfill

IE, = getAttribute("data-gender");,

+3
source

This is because you are using the jQuery function for the DOM element. You must either use your own javascript function to retrieve the attribute value, or you can convert the element to a jQuery object and then continue to use jQuery.

So instead

products[i].attr('data-gender');

You can:

$(products[i]).attr('data-gender');
+1
source

Source: https://habr.com/ru/post/1612259/


All Articles