AnR
AnR

Reputation: 2225

How to select all items in a list using jQuery Selector

I am creating a dynamic list on these lines:

<li class="MainMenuList" data-role=list-divider>
    <li data-icon=check id="1">
        <a name="n1" id="id-1">Text-1</a>
    </li>
    <li data-icon=check id="2">
        <a name="n2" id="id-2">Text-1</a>
    </li>
    <li data-icon=check id="3">
        <a name="n3" id="id-3">Text-1</a>
    </li>
</li>

How can I run JQuery .each() selector to access all the value in the list. Trying this doesn't produce ant result.

$( ".MainMenuList li a" ).each(function( index ) {
    var n1 = $(this).attr('name');
    var n2 = parseInt ($(this).attr('id'));
    alert( index + "-" + n1 + "-" + n2);
});

Upvotes: 0

Views: 99

Answers (3)

lebolo
lebolo

Reputation: 2160

Here's a jsFiddle of your code

  • As mentioned in the comments, your first <li> element should be a <ul>
  • You should also either change the <a> id to strictly a number (since your parsing it as an integer) or just retrieve the number part (via substr or something else)

Upvotes: 1

ken.dunnington
ken.dunnington

Reputation: 905

You're calling parseInt() on a string. If you know your IDs will always be in the form id-N you could just do

var id = $(this).attr("id");
var n2 = parseInt(id.split("-")[1]);

Upvotes: 1

epascarello
epascarello

Reputation: 207537

Your HTML is invalid, the outside li should be a ul for it to be valid.

<ul class="MainMenuList" data-role=list-divider>
    <li data-icon=check id="1">
        <a name="n1" id="id-1">Text-1</a>
    </li>
    <li data-icon=check id="2">
        <a name="n2" id="id-2">Text-1</a>
    </li>
    <li data-icon=check id="3">
        <a name="n3" id="id-3">Text-1</a>
    </li>
</ul>

This line

var n2 = parseInt ($(this).attr('id'));

is the same as

var n2 = parseInt("id-2");

and parseInt will not return the 2, it will return NaN.

You would have to use a regular expression

$(this).attr('id').match(/\d+/)[0]

or split to pull out the number

$(this).attr('id').split("-")[1]

or you could just reference the parents id if that is a valid assumption.

$(this).parent().attr('id')

Upvotes: 3

Related Questions