Reputation: 13866
Let's say we have the following markup:
<p>
foo
</p>
<p>
</p>
<p>
bar
</p>
<p>
</p>
and we want to select paragraphs which have some content visible to the user. Is there a way how to achieve this directly with a certain selector or does one have to cycle through them?
Currently I'm stuck with this:
var paragraphs = $('p');
var nonEmptyParagraphs = [];
var curP;
for(var i=0; i<paragraphs.length; i++) {
curP = $(paragraphs[i]);
if(curP.text().length > 0) {
nonEmptyParagraphs.push(curP);
}
}
Thanks for advice!
Upvotes: 1
Views: 89
Reputation: 4508
You forgot the javascript trim() function to remove the blank space inside your <p>
elements
if(curP.text().trim().length > 0) {
nonEmptyParagraphs.push(curP);
}
http://jsfiddle.net/qYdwR/2606/
Upvotes: 0
Reputation: 20740
You can select non-empty do it like following.
$('p').filter(function () {
if ($(this).text().trim())
return this;
})
Upvotes: 3