udexter
udexter

Reputation: 2347

Selecting <span />s inside a <li /> inside a <ul /> with jQuery

I have the next code:

<ul>
    <li id="cat-12">
        <span id="subcat-13">lorem</span>
        <span id="subcat-43">ipsum</span>
    </li>
    <li id="cat-41">
        <span id="subcat-22">lorem</span>
        <span id="subcat-23">ipsum</span>
    </li>
</ul>

How I can select all <span /> IDs? So I get an array with: subcat-13, subcat-43, subcat-22, subcat-23?

Thank you in advance!

Upvotes: 0

Views: 5151

Answers (3)

Jamiec
Jamiec

Reputation: 136074

No need to loop with each, instead use map(docs) like this:

var arr = $('ul li span').map(function(){
   return $(this).attr('id');
});

Live example: http://jsfiddle.net/qdAnx/

Upvotes: 7

voigtan
voigtan

Reputation: 9031

if you want a pure Array with just the ID you can select all the span:

var span = $("ul li span");

and then loop them with .each()

var span = $("ul li span"),
    arr = [];

span.each(function() {
    if(this.id) {
        arr.push(this.id);
    }
});

Upvotes: 1

Samich
Samich

Reputation: 30095

var array = new Array();

$('ul > li > span').each(function() {
    array.push($(this).attr('id'));
});

Upvotes: 2

Related Questions