I'm new to JQuery and struggling to set an attribute of an element inside a list. I have the following html
<ul class="collections">
<li><a href="#" id="2">LINEN </a></li>
<li><a href="#" id="3">ANIMAL PRINTS</a></li>
<li><a href="#" id="4">BASKET WEAVE</a></li>
<li><a href="#" id="5">FAUX LEATHER</a></li>
<li><a href="#" id="6">FAUX SUEDE</a></li>
<li><a href="#" id="7">HALLMARK</a></li>
<li><a href="#" id="8">JUMBO CORD</a></li>
<li><a href="#" id="9">PHYTHON</a></li>
<li><a href="#" id="10">CHENILLE CARLTON</a></li>
I want to add the attribute class = "current" to the item in the list where the id is 2.
I can set all items using $('.collections a').attr('class','current');
I can detect the item with the id of 2 using:
if($('.collections a').attr('id') == 2){
console.log('WE HAVE A MATCH');
}
But here I am unsure how to get a reference to the actual element.
I've managed set the class using the equals method:
$(".collections a:eq(0)").attr('class','current');
But would prefer to be able to set it using the id of the element in case the ordering of the list should change.
Any help would be greatly appreciated.
Thanks in advance.
Regards