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!

Manos Nikolaidis
22.4k12 gold badges76 silver badges82 bronze badges
asked Oct 19, 2015 at 13:43
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

answered Oct 19, 2015 at 13:45
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()

answered Oct 19, 2015 at 13:46

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

answered Oct 19, 2015 at 13:50

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');
answered Oct 19, 2015 at 13:58

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.