user1015214
user1015214

Reputation: 3081

jquery selector only chosing the first list element

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?

Upvotes: 0

Views: 78

Answers (1)

alex
alex

Reputation: 490163

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();

Upvotes: 1

Related Questions