tags:

views:

28

answers:

2

I have a html page as below:

<div id="test1">
    <table>
        <tr>
            <td><span id="234">ABKO</span></td>
        </tr>
        <tr>
            <td><span id="1234">ABKO2</span></td>
        </tr>
        <tr>
            <td><span id="2634">ABKO3</span></td>
        </tr>
    </table>    
</div>
<div id="test2">
    <table>
        <tr>
            <td><span id="233">ABKOw</span></td>
        </tr>
        <tr>
            <td><span id="1236">ABKOc</span></td>
        </tr>
        <tr>
            <td><span id="2635">ABKOv</span></td>
        </tr>
    </table>    
</div>

How can i get all the span details between using jQuery? eg if i consider first div=test1 then i want all the soan with their ID and text as div -> test1 Span => id 233 && ABKO Span => id 1234 && ABKO2 Span => id 22634 && ABKO3

+4  A: 

You can iterate through all the <span> elements like so:

$('div span').each(function(){
    var divId = $(this).closest('div').attr('id');
    var spanId = $(this).attr('id');
    var spanTxt = $(this).text()

    // do something with the above
});

You can see it in action here.

What this is doing is building a list of span elements that are nested in a div (CSS selector div span). It then iterates over this list using the .each() method.

Within each iteration $(this) refers to the matched span element. We then use the .closest() method to find the span's first ancestor that matches the given selector (div). This gets our parent div.

Finally .attr() and .text() gets the ID attribute and text values .

Pat
+1 for demo on jsfiddle
Hugo Migneron
+2  A: 

You can find an element by Id with something like $('#test1'). You can find elements by tag with $('span') or $('div').

If you want to find all the spans belonging to "test1":

$('#test1').find('span')

or

$('#test1 span')

You can iterate over a collection of elements with each():

$('#test1').find('span').each(function() { 
    var id = this.id;
    var value = $(this).html();
    // do whatever...
});

Hopefully you can work the rest out yourself from this.

fearofawhackplanet