views:

27

answers:

5

I'm basically trying to do exactly what the subject suggests, but I'm getting "undefined" in my alert, and I'm not entirely sure why. I am fairly new to jquery, so, I probably have the syntax wrong, but not sure where to go from here. I'll post both of my attempts, which both yield "undefined" in the alert...

//In my first attempt, I'm trying to get the id of the inner a tag
<ul>
                <li id="l1" class="active"><a href="#c1">Samp 1</a></li>
                <li id="l2" class=""><a href="#c2">Samp 2</a></li>
                <li id="l3" class=""><a href="#c3">Samp 3</a></li>
        </ul>

var selected = $(".active).children("a").attr("id");
    alert(selected);

//In my second attempt, I'm trying to get the id of the currently selected li
    var selected = $(".active").attr("id");
    alert(selected);
A: 

The issue with the anchors seems to be that none of the anchors you're selecting actually have an ID. Do you mean .attr("href") by any chance?

karim79
A: 

it should be

var selected = $('ul').find('.active').attr('id');
jAndy
+1  A: 

In the first attempt, you're getting the <a> within the <li>...which doesn't have an ID, you just need this:

var selected = $(".active").attr("id");
alert(selected);

So your second attempt is correct, you can see it in action here.

If you actually meant to get the id from the <a> element, then you need to give them IDs and your first attempt will work, you can see it here.

Nick Craver
A: 

You're getting the wrong attribute (or you have a wrong markup). There's no "id" attribute in your a tags. You have "href" attributes, so if you're trying to geth the value of "href" you should use this:

var selected = $(".active).children("a").attr("href");
    alert(selected);

Otherwise if you need to get the parent's id you should use:

var selected = $(".active).attr("id");
    alert(selected);
mamoo
+1  A: 
$(".active).children("a").attr("id");

Your <a> elements do not have an id, only an href. And using a selector instead of the children function may make your code easier to read.

Do you mean $(".active > a").attr("href")?


$(".active").attr("id");

jQuery will return the id attribute of the first element in the jQuery collection. Maybe you have another element with class active?

I suggest you try $("ul > li.active").attr("id")?

Vincent Robert