0

I have a list like this in a div:

<div id="x">5,2,3,1,4,9,8</div>

How do I simply remove a given element from this list? JQuery or JavaScript may be used.

Please note that the numbers in the list are unique and they are coming in from a database of type int(11), they are not in any sort of order.

Any help appreciated guys...

0

5 Answers 5

3

First, get the text:

var text=$("#x").text();

Then split it:

var items=text.split(',');

If there's no items, you'll have an empty string as the only element of the array. If so, empty the array:

if(items.length==1&&items[0]=="") {
    items=[];
}

Now convert everything to an integer: (note that this step isn't actually required, but if you're doing anything else with items, it's nice to have)

items=items.map(function(str) { return parseInt(str, 10); });

Put the item you want to remove in a variable:

var itemToRemove=3;

Find that in the array:

var index=items.indexOf(itemToRemove);

If it was found, splice it out of the array:

if(index!==-1) {
    items.splice(index, 1);
}

Join the items back together:

text=items.join(',');

Put it back in the element:

$("#x").text(text);
Sign up to request clarification or add additional context in comments.

Comments

3

Try this with toRemove equal to 5, 3, or 8 to see that it works for all cases:

var toRemove = 3; // the number you want to remove
$('#x').text($('#x').text().replace(new RegExp(toRemove + ',?'
                                               + '|,?' + toRemove + '$'), ''));

See example →

3 Comments

+1, but your regex is bad. It'll match things like 33,. Use new RegExp('[^,]' + toRemove + '(?=[$,])')
You're right, my apologies. If you answer I will delete mine and +1 you.
Actually, just realized the regex I posted won't quite work. Yours is actually closer to what's needed :) new RegExp('(^|,)' + toRemove + ',|,' + toRemove + '$') and replace with $1
1

Using jQuery's grep-method may be an option too:

var toRemove=1; 
$('#x').text( $.grep($('#x').text().split(','),
                     function (a) { return a != toRemove; }).join(','));

To remove multiple items:

var toRemove=[1,8,3]; 
$('#x').text( $.grep($('#x').text().split(','),
                     function (a) { return $.inArray(Number(a),toRemove)<0; })
                       .join(','));

(But I would prefer a RegExp-solution, it should be much faster)

Comments

1

This is a simple solution that just requires jquery.

function removeFromDiv(which)
{
    var data = $("#x").html();
    data_arr = data.split(",");
    for (var i = 0; i < data_arr.length; i++)
    {
        if (data_arr[i] == which)
        {
            data_arr.splice(i, 1);
            data = data_arr.join(",");
        }
    }
    $("#x").html(data);
}

then simply run:

removeFromDiv("4");

5 Comments

You shouldn't use for...in on arrays; if someone has extended Array.prototype it will iterate over those properties as well.
Interesting, what's the solution to iterating over an array then?
@two13: Either call forEach on the array if you're not modifying it (note that forEach is not supported by some older browsers, however), or use for(var i=0, l=myArray.length; i<l; i++).
@two13: Oh, I forgot one other thing. You'll have to decrement l when you remove an element if you're using that cache-length thing. Alternatively, to not cache the length, you could use this: for(var i=0; i<myArray.length; i++)
@icktoofay both versions work identical in my tests. It doesn't appear to affect the array length after it's removed and still steps through the array properly regardless of which version I use. Is there some instance where one of them would break? edit nevermind I see it throws an error with first version because the array is too long, gotcha, will update. :)
1

Doesn't really need to be much harder than this:

function removeIndexFromX(index) {
  // Build array from comma-delimited content
  var arr = $("#x").text().split(',');

  // Remove index (zero-based)
  arr.splice(index, 1);

  // Replace
  $("#x").text(arr.join(','));
}

function removeNumberFromX(num) {
  var arr = $("#x").text().split(',');
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] === num) {
      arr.splice(i, 1);
    }
  }

  $("#x").text(arr.join(','));
}

The benefit of split and join is that you can use those to manage delimiters (e.g. commas) for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.