Get id of child element and save in variable using jquery?

I basically try to do exactly what the item offers, but I get "undefined" in my warning, and I'm not quite sure why. I'm new to jquery, so I probably have the wrong syntax, but not sure where to go from here. I will send both my attempts, which both give "undefined" in the message ...

//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); 
+7
jquery attributes element
source share
4 answers
 $(".active").children("a").attr("id"); 

The <a> elements have no id , only href . And using a selector instead of the children function can 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. Do you have another element with class active ?

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

+12
source share

In the first attempt, you get <a> inside <li> ..., which has no identifier, you just need to:

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

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

If you really meant to get <T23> from the <a> element, then you must give them the identifiers and your first attempt will work, you can see it here .

+1
source share

The problem with anchors is that none of the anchors you have selected actually have an identifier. Do you mean .attr("href") accident?

0
source share

You get the wrong attribute (or you have the wrong markup). There is no id attribute in your tags. You have the href attributes, so if you are trying to set the value to href, you should use this:

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

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

 var selected = $(".active).attr("id"); alert(selected); 
-one
source share

All Articles