HTML
<ul 开发者_JAVA技巧class="tabbox">
<li></li>
,
<li></li>
,
<li></li>
</ul>
JQuery (My Idea - does NOT work)
$(".tabbox").replace(',' , ''); // This was my idea, and it does not work ..
How can I remove the , from the < ul > ?
It seems to me that you're asking the wrong question.
If the intent is to remove the spurious text nodes (which happen to contain commas) from between the <li>
nodes, you should do this:
$('.tabbox').contents().filter(function() {
return (this.nodeType === 3);
}).remove();
Working demo at http://jsfiddle.net/alnitak/gN7yM/
Note the use of .contents()
to ensure that text nodes are included in the results.
If instead you want to purify the code to remove anything that isn't an <li>
from the <ul>
, use this:
$('.tabbox').contents().not(function() {
return (this instanceof HTMLLIElement);
}).remove();
FWIW, since @ShadowWizard reports that this doesn't with with IE < 8.0 I tried:
$('.tabbox').contents().not('li').remove()
and it didn't work. Reading the jQuery source it seems that pure string selectors completely ignore text nodes, but this does work:
$('.tabbox').contents().not(function() {
return $(this).is('li');
}).remove();
EDIT I've changed a couple of the examples above to use .not()
instead of .filter()
so as to remove the double negative.
One way to clean the list and leave only the list items is such code:
var list = $(".tabbox");
var items = $(".tabbox li");
list.html("");
items.each(function() {
list.append($(this));
});
Live test case: http://jsfiddle.net/TS8Sd/
This will not only remove comma but any other text or elements that do not belong there.
var tabbox = $(".tabbox"),
tabHtml = tabbox.html();
tabbox.html(tabHtml.replace(/,/g , ''));
This would replace all of them.
EDIT:
Although, why would you have a ',' after each li?
var tabHtml = $(".tabbox").html();
$(".tabbox").html(tabHtml.replace(/,/g , '')); //@Tomgrohl already answered it
My example makes use of the function parameter for .html()
.
$('.tabbox').html(function (index, oldhtml) {
return oldhtml.replace(/,/g, '');
});
jsFiddle Demo
精彩评论