Reputation: 2100
I've almost got this but just need a little push over the edge. I'm parsing a string which contains (potentially) HTML. Here's the code:
function clean(snippet) {
OBJ = $(snippet);
txt = OBJ.text();
if(txt) {
parsed = txt;
} else {
parsed = snippet;
}
return parsed;
}
And here are my test cases:
alert(clean("<div>Randomness</div>")); // Alerts "Randomness"
alert(clean("Randomness")); // Alerts "Randomness"
alert(clean("<div></div>")); // Alerts "<div></div>" - should be blank
I can't really figure out how to determine if its just an empty tag that gets passed in vs just plain text and how to deal with it. So I need a test to see if a tag is empty, perhaps. Not sure if that's the best way.
Upvotes: 1
Views: 1933
Reputation: 104168
In case you have html you can do something like this:
root = $(snippet);
if (root.text().length > 0) {
return snippet;
}
if (root.find(":first")) {
return snippet;
}
This doesn't handle the case the first element inside the div is empty.
Upvotes: 0
Reputation: 137997
You can test if your query returns any objects:
function clean(snippet) {
OBJ = $(snippet);
if(OBJ.length == 0)
return snippet;
txt = OBJ.text();
return txt;
}
Upvotes: 1