Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery | Find all "," (comma) in an <ul> and erase them / replace with ' '

HTML

   <ul 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 > ?

like image 677
Tomkay Avatar asked May 03 '11 10:05

Tomkay


2 Answers

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.

like image 58
Alnitak Avatar answered Oct 05 '22 11:10

Alnitak


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.

like image 30
Shadow Wizard Hates Omicron Avatar answered Oct 05 '22 11:10

Shadow Wizard Hates Omicron