jaread83 jaread83 - 5 months ago 11
Javascript Question

Remove empty paragraphs in reverse and move on to next element

I have a page with text but some of the containers have empty paragraph tags with each one at the end. It's important that I don't remove anything inbetween content, just at the end after the text finishes. My thinking for this would be to loop through the containers first and then check all the paragraph tags in reverse order, remove any that matches a regex and when it hits some content - move on to the next element. I have created a jsfiddle for this but it only removes them from the last panel.

jquery

$(document).ready(function() {
$(".content").each(function() {
$($("p").get().reverse()).each(function() {
var $this = $(this);
if ($this.html().replace(/\s| /g, '').length == 0) {
$this.remove();
}
else {
return false;
}
});
});
});


HTML

<div class="content">
<p>Blah</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Another Paragraph I want to keep</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</div>

<div class="content">
<p>Blah</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Another Paragraph I want to keep</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</div>

<div class="content">
<p>Blah</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>Another Paragraph I want to keep</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>another paragraph</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</div>


https://jsfiddle.net/659Lejgz/1/

I feel like I am so close but its just out of my reach. Any help would be really great!

Answer

You need to change $($("p").get().reverse()).each(function() {

To: $($(this).find("p").get().reverse()).each(function() {

Actually when happens in the original code, is although we're looping through the .content elements, in each iteration of the loop, we query the p element in the context of the entire documents, and since we reverse the result, we always get the last p element of the last .content element.

By changing $("p") to $(this).find("p"), we force jQuery to search for p elements only inside the .content element we are currently iterating over.

Comments