w00tw00t111
w00tw00t111

Reputation: 359

jQuery : Remove empty Items from object

I am accessing wikipedia's api and getting information about a topic via ajax. The api returns an object that I am parsing like this:

wikipage = data.parse.text['*'].children('p:lt(3)');
wikipage.find('sup').remove();

However, because wikipedia uses pretty loose formatting I have found I must grab the first 3 paragraphs that are returned in order to have enough information. At times, wikipedia will return an empty first paragraph, and a populated 2nd and 3rd paragraph. Other times, 1st and 2nd are empty and 3rd is full. And occasionally all 3 are full of text.

What I need to accomplish is to remove any empty paragraph values from the wikipage object and then make wikipage = to the first p value in the object.

I have tried the following:

wikipage.find('p:empty').remove();
return wikipage.get(0);

but that is not working. It is not removing the empty paragraphs.

I'm new to jQuery and am about to pull my hair out, lol! Please help!

Upvotes: 1

Views: 671

Answers (1)

Ian
Ian

Reputation: 50905

Try:

wikipage.find("p").each(function () {
    var $this = $(this);
    if ($this.html().trim() == "") {
        $this.remove();
    }
});

You could also use the selector:

$("p", wikipage).each(function () {

});

but I'm not sure of the difference in this situation. When chaining, it makes sense to use .find(), but this selection is at the beginning, so I don't know how different these are. I'm sure it doesn't matter, just wanted to point it out!

Upvotes: 1

Related Questions