Adam
Adam

Reputation: 20882

jquery + loop through data attributes

I have a number of DIV's with the class mainMenuInternalTab

Each has the data attribute called data-pagename.

How can I loop through all instances of this data attribute to see there is one with the name converstations set?

thankyou

<div id="mainMenuInternalConversations" class="mainMenuInternalTab" data-pagename="conversations"></div>
<div id="mainMenuInternalConversations2" class="mainMenuInternalTab" data-pagename="conversations2"></div>
<div id="mainMenuInternalConversations3" class="mainMenuInternalTab" data-pagename="conversations3"></div>

Upvotes: 0

Views: 2457

Answers (2)

Adil
Adil

Reputation: 148110

You can use each() to iterate through elements with class mainMenuInternalTab.

$('.mainMenuInternalTab').each(function(){
   alert($(this).data('pagename'));
   if($(this).data('pagename') == "convsersions set")
   {
      // do what ever you want here.
   } 
});

Upvotes: 0

adeneo
adeneo

Reputation: 318182

if (  
      $('.mainMenuInternalTab').filter(function() {
         return $(this).data('pagename') == 'conversations';
      }).length​
   ) {

         //do something if an element with the data attribute
         // pagename has a value of 'conversations'

     }

or a simpler version (but probably a little slower) :

if ( $('.mainMenuInternalTab[data-pagename="conversations"]').length ) {
    //do something
}

Upvotes: 1

Related Questions