user2953989
user2953989

Reputation: 2979

appending a class to an element based on its data-html using javascript

I want to append the class 'activeTab' to a tag on document ready. I need to select the tag by it's data-html but I'm not sure how to do this.

So this is how the html loads currently:

<ul class="tabbedGroupings_tabs">
  <li class="tg_tab" data-html="academicprofessionalanddevelopment">Academic, Professional and Development</li>
  <li class="tg_tab" data-html="cultural">Cultural</li>
  <li class="tg_tab" data-html="physicalactivityandperformance">Physical Activity and Performance</li>
  <li class="tg_tab" data-html="politicsreligionandcampaigning">Politics, Religion and Campaigning</li>
  <li class="tg_tab" data-html="society">Society</li>
  <li class="tg_tab" data-html="specialinterest">Special Interest</li>
  <li class="tg_tab" data-html="all">All</li>
</ul>

I would like to add 'activeTab' class to the data-html="all" element.

Upvotes: 0

Views: 40

Answers (1)

Arun CM
Arun CM

Reputation: 3435

You can use jQuery Attribute selector. $("[attribute]") , Which will selects elements that have the specified attribute with a value exactly equal to a certain value.attribute-equals-selector

$(document).ready(function() {
  $(".tabbedGroupings_tabs > [data-html='all']").addClass('activeTab');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="tabbedGroupings_tabs">
  <li class="tg_tab" data-html="academicprofessionalanddevelopment">Academic, Professional and Development</li>
  <li class="tg_tab" data-html="cultural">Cultural</li>
  <li class="tg_tab" data-html="physicalactivityandperformance">Physical Activity and Performance</li>
  <li class="tg_tab" data-html="politicsreligionandcampaigning">Politics, Religion and Campaigning</li>
  <li class="tg_tab" data-html="society">Society</li>
  <li class="tg_tab" data-html="specialinterest">Special Interest</li>
  <li class="tg_tab" data-html="all">All</li>
</ul>

Upvotes: 1

Related Questions