jquery - Get ID of .selected class without clicking -
i want id of link has been classed .selected. found several solutions don't work or include click function , 'this'. don't want use click functions because when open page, 1 link selected.
this list, preferably id of list , not link
<ul id="dates"> <li id="all"><a id="all" href="#all">1943-2003</a></li> <li id="li1943" ><a id="a1943" href="#1943">1943</a></li> <li id="li1953" ><a id="a1953" href="#1953">1953</a></li> <li id="li1963" ><a id="a1963" href="#1963">1963</a></li> <li id="li1973" ><a id="a1973" href="#1973">1973</a></li> <li id="li1983" ><a id="a1983" href="#1983">1983</a></li> <li id="li1993" ><a id="a1993" href="#1993">1993</a></li> <li id="li2003" ><a id="a2003" href="#2003">2003</a></li> </ul>
i tried in jquery
var selectyear = $("#dates").closest(".selected").attr("id");
and this
var selectyear = $("#dates li a.selected").attr("id");
note: changed html markup
var li = $("#dates a.selected").parent(); var selectedyear = li.attr('id');
or if don't need li object:
var selectedyear = $("#dates a.selected").parent().attr('id')
update
i think need create function selected year:
function getselectedyear() { return $("#dates a.selected").parent().attr('id'); }
now can use in both click , and page load functions:
$('#mybutton').click(function() { var selectedyear = getselectedyear(); // ... }); $(function() { var selectedyear = getselectedyear(); // ... });
Comments
Post a Comment