0

Can someone find what my mistake is? I have the following html list

 <ul id="left-help-menu">
        <li><a href=#">My Library</a>
            <ul class="left-menu-sub">
                <li id="1">A</li>
                <li id="2">B</li>
                <li id="3">C</li>
                <li id="4">D</li>
                <li id="5">E</li>

            </ul>

        </li>
      </ul>

and the following jquery code

 $(document).ready(function() {
$("#left-help-menu li li a").click(function() {
    var vid = $("#left-help-menu li li").attr("id");
            });
   });

For some reason, this selector is only chosing the first li tag ( when I test it by pasting 'vid' on the page, it always gives me '1'). Why is this?

2
  • What do you expect? An array of every id attribute matched? Commented Nov 5, 2012 at 4:21
  • 1
    Please read the documentation. Get the value of an attribute for the first element in the set of matched elements Commented Nov 5, 2012 at 4:22

1 Answer 1

1

That's the way an attr() getter works. It works on the first matched element.

If you want an array of all matched id attributes...

var vid = $("#left-help-menu li li").map(function() { return this.id; }).get();
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, I realized my mistake, I really wanted to return the id on the $(this) selector. Now it works. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.