Luc
Luc

Reputation: 1825

Simple javascript loop not working

I'm not that experienced yet with JavaScript, so I’m probably overlooking 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].attr is not a function

I should be able to access it right? The product is just a list item.

Thanks!

Upvotes: 4

Views: 75

Answers (4)

Jaromanda X
Jaromanda X

Reputation: 1

By far the easiest way to get data-xyz attributes for an element is to use .dataset object

e.g. in your case

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

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

usual warnings - IE11+ only (other browsers have supported it for years) - there's no polyfill

if you need early IE support, then use = getAttribute("data-gender"); as others have suggested

Upvotes: 3

Karolis
Karolis

Reputation: 43

It's because you use Jquery function on DOM element. You should either use native javascript function to retrieve attribute value or you can convert element to Jquery object and then keep using Jquery.

So, instead of

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

you can:

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

Upvotes: 1

BobbyTables
BobbyTables

Reputation: 4685

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

Is what you need, you have used jquerys .attr()

Upvotes: 3

Igor
Igor

Reputation: 15893

attr is a jQuery method, use getAttribute

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

Upvotes: 4

Related Questions