1

I have a variable which contains an item number ... like this:

myvariable = '3'; //Note: This is currently a string so it might need converting?

Then I have the code which populates the listview:

$('#listview').live("pageinit", function(){
$.getJSON("myjson.json", function(data){
    $.each(data.unis, function(index, value){


        $('<li><a class="listitem" href="#">' + value.name + '</a></li>').insertAfter('#' + value.sortLetter);

        $('#' + value.sortLetter).show();

    });

    $("#listview").listview("refresh");


});

All the above works fine.

Now, what I need to do it to insert a class into the item which is at the position myvariable value.

So, if myvariable is 3 then the listview will look like this:

<ul>
<li><a class="listitem" href="#">' + value.name + '</a></li>
<li><a class="listitem" href="#">' + value.name + '</a></li>
<li><a class="listitem AddedClassHere" href="#">' + value.name + '</a></li>
</ul>

if myvariable was to be 1 then:

<ul>
<li><a class="listitem AddedClassHere" href="#">' + value.name + '</a></li>
<li><a class="listitem" href="#">' + value.name + '</a></li>
<li><a class="listitem" href="#">' + value.name + '</a></li>
</ul>

and so on...

How could I do this?

3 Answers 3

2

You can use :eq() selector, note that :eq() is zero-based.

$('ul li:eq("'+ (myvariable-1) +'") a').addClass('class');

Or:

$('ul li').eq(myvariable-1).find('a').addClass('class');
Sign up to request clarification or add additional context in comments.

Comments

2

One way is to build the class list dynamically for each item, optionally adding your class if the index matches the magic number that you specify in your variable. Change your code to this:

$.each(data.unis, function(index, value){
    var classList = 'listItem';
    if(index == (myvariable - 1)) {
        classList += ' addedClass';
    }
    $('<li><a class="' + classList + '" href="#">' + value.name + '</a></li>').insertAfter('#' + value.sortLetter);

    $('#' + value.sortLetter).show();
});

Comments

1

There is also an eq() method:

$('ul li').eq(myvariable - 1).find("a").addClass('class');

se http://api.jquery.com/eq-selector/ for more docs.

Note: Watch out if you are using multiple (or nested) ul on same page, then you need a different approach...

1 Comment

It adds the class to li element instead of anchor link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.