سؤال

I have the following HTML

<table>
    <tr>
        <td><span></span></td>
        <td><a><span></span></a></td>
        <td><span></span><span><span/></td>
    </tr>
<table/>

I need to select the first appearance of span in each td. I would exepcted 3 spans from the above HTML.

$('td span') returns all (4) spans

$('td span:first-child') return all spans also

$('td span:first') return only first

$('td > span') return only 2 spans.

Could I do this by selector or filter?
What do I have to use to achieve this?

هل كانت مفيدة؟

المحلول

Try this:

​$('td').find('span:first')

http://jsfiddle.net/qDAt8/

Please note that your markup is not valid.

نصائح أخرى

After fixing the HTML, this will work:

$('td').find('span:first');

DEMO

The DEMO above uses the following sample HTML and visualy highlights the matching elements:

<table>
    <tr>
        <td><span>span 1.1</span><span>span 1.2</span></td>
        <td><a><span>span 2.1</span><span>span 2.2</span></a></td>
        <td><span>span 3.1</span><span>span 3.2</span></td>
    </tr>
</table>
$("table td").find("span:first")

Gives you the three first spans. jQuery finds element more efficiently when you provide a more detailed search.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top