Given a DIV with a lot of paragraph tags:
<div>
<p></p>
<p>ADSADASA开发者_如何学JAVAD ADS ADS A </p>
<p>ADSADASAD ADS ADS A </p>
<p>ADSADASAD ADS ADS A </p>
<p>ADSADASAD ADS ADS A </p>
</div>
How to magically find the first <P>
which isn't empty using just jQUery? ideas?
I find it a little less mind-bending to use methods rather than selectors for this:
$('div').find('p').not(':empty').first()
Edit: As per the poster's comment, here's a version that defines "empty" as "having no text content, although there may be HTML tags present":
$('div#foo').find('p').filter( function(){
return ( $.trim($(this).text()).length );
}).first()
Example: http://jsfiddle.net/8dem8j8L/
I think you can use:
$('div').find('p:not(:empty):first')
var emptyP = null;
jQuery('div p').each(function() {
if (emptyP == null && $(this).text() == '') {
emptyP = this;
}
});
Edit: tster's solution looks better, I didn't know about the :empty
selector.
http://www.jsfiddle.net/bradchristie/8k3VW/1/
$(document).ready(function(){
$('div p:not(p:empty):first').text('First not empty');
});
You can try this:
$('div p:not(:empty)').eq(0);
You can use either of the following...
var firstNonEmptyP1 = $('p').not(':empty').first();
var firstNonEmptyP2 = $('p:not(:empty):first');
Working example: http://jsfiddle.net/WTdMh/
You can use the :not
selector with the :empty
selector, like so:
var notEmpty = $('#container').find('p:not(:empty):first');
// or
var notEmpty = $('#container > p:not(:empty):first');
Live example
The above uses an ID to find the container of the divs, but of course this is jQuery, you can use any selector.
精彩评论