开发者

How to select children from the list of matched elements?

开发者 https://www.devze.com 2023-02-09 00:12 出处:网络
This one has really got me confused: I have a group of \'items\' and I want to select the first <pre> in each group.

This one has really got me confused:

I have a group of 'items' and I want to select the first <pre> in each group.

<div class="item">
    <table>
        <tr>
            <td>
                <h1>Test</h1>
                <pre>0</pre>
                <pre>
                    <code>1</code>
                </pre>
                <pre>
                    <code>2</code>
                </pre>
            </td>
        </tr>
    </table>
</div>
<div class="item">
    <pre>
        <code>3</code>
    </pre>
    <pre&g开发者_运维问答t;
        <code>4</code>
    </pre>
</div>
<div class="item">
    <pre>
        <code>5</code>
    </pre>
</div>
<div id="output"></div>

My jQuery code looks like this:

$('.item:has(pre)').each(function(){

    text = $(this).filter('pre').html()
                  .replace(/</g,'&lt;').replace(/>/g,'&gt;') + "<br><br>";
    $('#output').append(text);

});

I expect the output to be the contents of the <pre> blocks, but instead, I get nothing. If I use the .size() function on the matched elements, I get 0 every time.

The above code can be found on jsFiddle: http://jsfiddle.net/george_edison/syLMD/8/


$('div.item pre:first-of-type').each(function(){

text = $(this).filter('pre').html().replace(/</g,'&lt;').replace(/>/g,'&gt;') + "<br><br>";
$('#output').append(text);
});


.filter() only looks at the current set of elements, whereas .find() looks at the descendants.

$('.item:has(pre)').each(function(){

    text = $(this).find('pre:first').html().replace(/</g,'&lt;').replace(/>/g,'&gt;') + "<br><br>";
    $('#output').append(text);

});
0

精彩评论

暂无评论...
验证码 换一张
取 消