...

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



m2244
10-02-2012, 07:09 PM
Hello,

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.-->
</ul>
</div>





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>');
}

$('.scrubberBtn')
.click(function(){
$(this).removeClass("scrubberBtn").addClass("scrubberBtnSelected").parent().siblings().children().removeClass('scrubberBtnSelected').addClass('scrubberBtn');
current_pg_ind = this.getAttribute("index");
$("#dev_current_pages").text(parseInt(current_pg_ind) + 1);
requestPage(current_pg_ind);
})
}


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()
{
alert($("#scrubberList").getAttribute("index"));
}

xelawho
10-02-2012, 07: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

alert($("#scrubberList").attr("index"));
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()

m2244
10-03-2012, 05: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))
{
$(this).removeClass("scrubberBtn").addClass("scrubberBtnSelected").parent().siblings().children().removeClass('scrubberBtnSelected').addClass('scrubberBtn');
return false;;
}
});

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



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum