Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get an id of child element and store in a variable using jquery?

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);
like image 864
pixie54 Avatar asked May 25 '10 14:05

pixie54


People also ask

How can I get the ID of an element using jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do I select an element in jQuery by using a variable for the ID?

The #id selector selects the element with the specific id. The id refers to the id attribute of an HTML element. Note: The id attribute must be unique within a document. Note: Do not start an id attribute with a number.

How do you get children of children in jQuery?

jQuery children() MethodThe children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.


2 Answers

$(".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. Do you have another element with class active?

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

like image 102
Vincent Robert Avatar answered Oct 07 '22 18:10

Vincent Robert


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.

like image 31
Nick Craver Avatar answered Oct 07 '22 20:10

Nick Craver