Satch3000
Satch3000

Reputation: 49384

Add a class to list at variable position

I have a variable set that represents an item in the list.

I also have the list:

<ul>
    <li class="mylist"><a href="#">Item 1</a></li>
    <li class="mylist"><a href="#">Item 2</a></li>
    <li class="mylist"><a href="#">Item 3</a></li>
    <li class="mylist"><a href="#">Item 4</a></li>
    <li class="mylist"><a href="#">Item 5</a></li>
    <li class="mylist"><a href="#">Item 6</a></li>
</ul>

What I need to do is to add a css class to the list thats in the position of the variable value.

For example:

If myVariable = '1' then list will look like this:

<ul>
    <li class="mylist"><a href="#" class="myclass">Item 1</a></li>
    <li class="mylist"><a href="#">Item 2</a></li>
    <li class="mylist"><a href="#">Item 3</a></li>
    <li class="mylist"><a href="#">Item 4</a></li>
    <li class="mylist"><a href="#">Item 5</a></li>
    <li class="mylist"><a href="#">Item 6</a></li>
</ul>

If myVariable = '3' then list will look like this:

<ul>
    <li class="mylist"><a href="#">Item 1</a></li>
    <li class="mylist"><a href="#">Item 2</a></li>
    <li class="mylist"><a href="#" class="myclass">Item 3</a></li>
    <li class="mylist"><a href="#">Item 4</a></li>
    <li class="mylist"><a href="#">Item 5</a></li>
    <li class="mylist"><a href="#">Item 6</a></li>
</ul>

and so on.

How can I do this?

Upvotes: 0

Views: 108

Answers (3)

moonwave99
moonwave99

Reputation: 22817

$("li.mylist").eq(position -1).find("a").addClass("myClass")

Upvotes: 1

Michał Miszczyszyn
Michał Miszczyszyn

Reputation: 12701

You can use the eq method in jQuery for selecting element by index:

const myVariable = 3;
$('.mylist').eq(myVariable - 1).find('a').addClass('myClass');

Mind that eq assumes that your indices are 0-based (which means the first one is 0 and not 1). That's why it's myVariable - 1.

Upvotes: 2

Bj&#246;rn
Bj&#246;rn

Reputation: 29381

var value = 3;
$('ul li.mylist a').filter(function () {

    return $(this).text() === 'Item ' + value;

}).addClass('myclass');

Upvotes: 2

Related Questions