4

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!

1
  • 2
    that's correct, attr isn't ... use products[i].dataset.gender to get that particular attribute Commented Oct 19, 2015 at 13:45

4 Answers 4

4

attr is a jQuery method, use getAttribute

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

Sign up to request clarification or add additional context in comments.

1 Comment

Don't use W3school, add links from MDN as reference
3
 var productGender = products[i].getAttribute('data-gender');

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

3 Comments

Ah it's working! So it's always better to use getAttribute if that's sufficient?
well, is the attribute there in the DOM? Can you show the elements?
@luc if you have jQuery availible you should user attr(), if you just write vanilla JS you need to use getAttribute
3

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

Please also add MDN link for dataset, it'll be easier for OP to read more about it +1
1

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.