View Full Version : How to find an element based on its attribute

10-02-2012, 08:09 PM

I have a <ul> element in which I use JS to place a number of <li> elements. These <li> elements have an attribute called 'index' which I use to jump around to different html pages.

HTML page.

<div id="scrubber">
<ul id="scrubberList">
<!--This is where the tick marks go for the page scrubber on the console.-->

function createScrubberTicks(){
for(i=0; i< pages_arr.length; i++){
$('#scrubberList').append('<li><span id="' + pages_arr[i].title + '" index="' + i + '" class="scrubberBtn">'</span></li>');

current_pg_ind = this.getAttribute("index");
$("#dev_current_pages").text(parseInt(current_pg_ind) + 1);

And now I need to find the <li> element with the correct index so that I can remove/add the class similar to above. The alert below does not work by the way.

How can I reference the correct <li> element based on this index number? (There can be up to 80 of these <li> elements)

function setScrubberIndex()

10-02-2012, 08:37 PM
1. I think your append string is badly formed - shouldn't it be like this?

$('#scrubberList').append('<li><span id="' + pages_arr[i] + '" index="' + i + '" class="scrubberBtn"></span></li>');
2. I think you are better off using the native jQuery attr

3. The scrubberList has no index, it is the li's that you append to it. Have a look at DOM transversal methods like nextAll() and children()

10-03-2012, 06:31 PM
Thanks for the help.

In case anyone needs this, here is what I ended up using.

$("#scrubberList li span[index]").filter(function() { return $(this).attr('index'); }).each(function()
//alert("In the wierd function.");
if($(this).attr("index") == parseInt(current_pg_ind))
return false;;

rnd me
10-04-2012, 08:26 AM
$("#scrubberList li span[index='"+ parseInt(current_pg_ind)+"']")