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!
4 Answers 4
attr is a jQuery method, use getAttribute
1 Comment
var productGender = products[i].getAttribute('data-gender');
Is what you need, you have used jquerys .attr()
3 Comments
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
1 Comment
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');
attrisn't ... useproducts[i].dataset.genderto get that particular attribute