AnApprentice AnApprentice - 5 months ago 10
HTML Question

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?

Answer

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/

Comments