AnApprentice
AnApprentice

Reputation: 110970

jQuery - Given a DIV with a bunch of <P> tags, how to find the first <P> that isn't empty

Given a DIV with a lot of paragraph tags:

<div>
 <p></p>
 <p>ADSADASAD 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?

Upvotes: 1

Views: 1338

Answers (7)

Ken Redler
Ken Redler

Reputation: 23943

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/

Upvotes: 4

tster
tster

Reputation: 18237

I think you can use:

$('div').find('p:not(:empty):first')

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074495

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.

Upvotes: 0

James Kovacs
James Kovacs

Reputation: 11661

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/

Upvotes: 0

Nick G
Nick G

Reputation: 960

You can try this:

$('div p:not(:empty)').eq(0);

Upvotes: 0

Brad Christie
Brad Christie

Reputation: 101614

http://www.jsfiddle.net/bradchristie/8k3VW/1/

$(document).ready(function(){
    $('div p:not(p:empty):first').text('First not empty');
});

Upvotes: 1

Matt Huggins
Matt Huggins

Reputation: 83289

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.

Upvotes: 1

Related Questions