0

I have a list of events on a page. My end goal is to hide a purchase button (by adding a class to it) if the event has passed, using JQuery/Javascript. Each event has a 3 data attributes(month, day, year). I tried using the following method to cycle through an array:

   var matches = document.querySelectorAll(".event-event");
   var i = 0;
   for (i = 0; i <  matches.length; i++) {
       var event = matches[i].getElementsByClassName('date');
       var eventDate = event.getAttribute('data-date');
    }

But it says that "getAttribute" is not a function, I've also tried ".attr" and it said the same thing.

4
  • Its because you are calling it on an array of objects rather than an object.. checkout something like event[0].getAttribute('data-date'); Commented Sep 24, 2015 at 16:53
  • Also before calling this method you should check whether event has elements loaded up or not by checking the number of elements in event array Commented Sep 24, 2015 at 16:55
  • I'm unclear on what you mean when you say "each event has 3 data attributes". You got your matches array using document.querySelectorAll(), which means that matches is an array of html elements, and html elements don't have month, day, and year attributes. Could you put a bare-bones version of your code on codepen.io or jsfiddle.net? It will be a lot easier to help you if we can see the html that your javascript with working with. Commented Sep 24, 2015 at 17:04
  • Inside each div.event-event there is a span with a class of "date". It also has data-month as an attribute on that span. Commented Sep 24, 2015 at 18:14

3 Answers 3

2
var matches = document.querySelectorAll(".event-event");
for (var i = 0; i < matches.length; i++) {
    var event = matches[i].getElementsByClassName('date');
    if (event.length > 0) {
        for (var j = 0; j < event.length; j++) {
            var eventDate = event[i].getAttribute('data-date');
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

The getElementsByClassName method returns an array.

Comments

1

Try this:

var matches = document.querySelectorAll(".event-event");
for (var i = 0; i < matches.length; i++) {
    var events = matches[i].getElementsByClassName('date');
    for(var j = 0; j < events.length; j++) {
        var eventDate = events[j].getAttribute('data-date');
    }
}

events is an array that you must iterate through.

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.