Collin Berg
Collin Berg

Reputation: 67

checking data attribute in a array

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.

Upvotes: 0

Views: 300

Answers (3)

Akhilesh Sharma
Akhilesh Sharma

Reputation: 1628

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

Upvotes: 2

Matt O&#39;Connell
Matt O&#39;Connell

Reputation: 287

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.

Upvotes: 1

sh0rug0ru
sh0rug0ru

Reputation: 1626

The getElementsByClassName method returns an array.

Upvotes: 1

Related Questions