sri harsha
sri harsha

Reputation: 55

How to write document.getElementsByClassName(names)[n] in jQuery

How to write

document.getElementsByClassName("navtab")[3].classList.add("active"); 

in jquery.

My attempt:

$(".navtab")[3].addClass("active");

This gave an error like:

index-page9.html:745 Uncaught TypeError: $(...)[3].addClass is not a function

Upvotes: 1

Views: 624

Answers (2)

user13234994
user13234994

Reputation:

You can use it in jquery like this:

  var element = $('.navtab')[3];
  $(element).addClass("active");

Upvotes: 1

palaѕн
palaѕн

Reputation: 73936

$(".navtab")[3]

actually returns a DOM element and .addClass() jQuery method can not be used on DOM elements. You need to use .eq() method to get nth index jQuery object like:

$(".navtab").eq(3).addClass("active");

Demo:

$(".navtab").eq(3).addClass("active");
.active { background-color: skyblue }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="navtab">List item 1</li>
  <li class="navtab">List item 2</li>
  <li class="navtab">List item 3</li>
  <li class="navtab">List item 4</li>
  <li class="navtab">List item 5</li>
</ul>

Upvotes: 2

Related Questions