azsl1326
azsl1326

Reputation: 1410

jQuery: How do I remove elements from a list <li>

I have the following list and would like to remove an element from it. In this particular instance I would like to remove the second element:

<a id="q1" rel="1" class="pagenum" href="#">2</a>

And here's the code for the list:

        <div id="carousel">
        <ul class="overview">
          <li id="l1">
              <a id="q0" rel="0" class="pagenum" href="#">1</a>
              <a id="q1" rel="1" class="pagenum" href="#">2</a>
              <a id="q2" rel="2" class="pagenum" href="#">3</a>
              <a id="q3" rel="3" class="pagenum" href="#">4</a>
              <a id="q4" rel="4" class="pagenum" href="#">5</a>                
          </li>
         </ul>
        </div>

Thanks, in advance.

EDIT: I was hoping to use something along the lines of $.each:

$("carousel li").each(function(index){
   if(index == SOME_NUM){
       this.remove()
   }
 });

However this doesn't seem to work.

ADDITIONAL EDIT:

Thanks and apologies to all those who answered. I did not phrase my question correctly. I did find the remove() function prior to posting here - it is well documented on google :). However, I am trying to loop through the elements of the "li" and then remove particular elements via a $.each loop.

Thanks for any and all additional replies.

Upvotes: 0

Views: 1370

Answers (3)

Ben Barden
Ben Barden

Reputation: 2111

I think this should do what you want it to do.

$counter = 0;
$("#carousel li").each(function(){
    if($counter == SOME_NUM)
    {
        this.remove();
    }
    $counter++;
});

You'll want to use jquery $variables here rather than javascript vars because javascript vars are function scoped, while the $variables are document scoped.

Upvotes: 2

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

ID is unique.. You can simply use $('#q1').remove();

Based on your comment

I was trying to avoid using id as there are a large number of these . I scaled down the example. I was hoping to use something along the lines of: $("overview li").each(function(index){ this.remove } however that doesn't seem to work.

Try using .eq function or :eq selector to select the specific link tag from the list,

$('.overview li a:eq(1)') //-> Will return you the 2nd link

Upvotes: 4

zzzzBov
zzzzBov

Reputation: 179046

Basic form of removal uses remove:

$(selector).remove();

So for the second element, you could use the [id]:

$('#q1').remove();

If you want to remove the second item in the list, independent of that item's [id], you could use:

$('#l1 :eq(1)').remove();

note that :eq uses 0-based indices

The removal function itself is easy to use, the hard part is determining what selector works best.

Upvotes: 1

Related Questions