Question

I want to get the ID of a link that has been classed as .selected. I found several solutions but they don't work or they include a click function and 'this'. I don't want to use any click functions because when I open the page, one link is already selected.

this is my list, preferably I would like the ID of the list and not the 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 this in jquery

    var selectYear = $("#dates").closest(".selected").attr("id");

and this

    var selectYear = $("#dates li a.selected").attr("id");

note: I changed the HTML markup

Was it helpful?

Solution

var li = $("#dates a.selected").parent();
var selectedYear = li.attr('id');

Or if you don't need the li object:

var selectedYear = $("#dates a.selected").parent().attr('id')

Update

I think you need to create a function to get the selected year:

function getSelectedYear() {
    return $("#dates a.selected").parent().attr('id');
}

Now you can use this in both your click and and page load functions:

$('#myButton').click(function() {
    var selectedYear = getSelectedYear();
    // ...
});

$(function() {
    var selectedYear = getSelectedYear();
    // ...
});

OTHER TIPS

Use below code:

var selectYear = $("#dates li.selected a").attr("id");

Try with .find() like this:

var selectYear = $("#dates").find("a.selected").attr("id");

or

var selectYear = $("#dates").find("a.selected")[0].id;

Note:

In a same page every ID should be unique but in your markup code you can see you have same id for two elements for <li> & <a> and that is said to be Invalid Markup.


As per your comment:

$(function(){
    var selectYear = $("#dates").find("a.selected").attr("id") || "No id found.";
    alert(selectYear);
});

Fiddle with "No id found."

Fiddle with "Id found."

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top