18

I have:

<ul id="ulId">
    <li id="firstli">
    </li>
    <li id="secondli">
    </li>
</ul>

and I am trying to remove secondli.

This is what I have tried based on some reading.

$('#ulId secondli').remove();

and

$('#ulId > secondli').remove();

but these 2 methods did not work. Any suggestions?

Adam
  • 15,564
  • 13
  • 95
  • 165
Pittfall
  • 2,521
  • 5
  • 27
  • 56

5 Answers5

49

Try this:

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

In jQuery, you refer to the ID of an element with a # in front of it. See http://api.jquery.com/id-selector/

j08691
  • 190,436
  • 28
  • 232
  • 252
  • Is there a way to specify which Ul it's coming from? – Pittfall Mar 25 '13 at 21:03
  • 1
    Yes, you can specify the UL's ID in front of it, however since IDs on all elements must be unique, there shouldn't be any need to be more specific. – j08691 Mar 25 '13 at 21:04
  • 1
    +1 for this line "In jQuery, you refer to the ID of an element with a # in front of it." – Mohammad Adil Mar 25 '13 at 21:04
  • It's *almost* like jQuery selector syntax is very closely related to standard CSS selectors .. that is: "In CSS, you refer to the ID of an element with a # in front of it." –  Mar 25 '13 at 21:08
  • 1
    I believe this to be the correct answer but I just want to let everyone know that my problem was that my id had a period in it which I did not mention in the question. This has to be escaped with a "\\". For example `$('#ulid #li\\.toRemove');` – Pittfall Mar 25 '13 at 21:14
  • 1
    @Pittfall I would recommend avoid using a `.` in an ID. While [it *is* permitted](http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html) in both HTML4/5 it is somewhat confusing and may lead to strange behavior in tools which do not otherwise account for it. Consider using either `_` or a `-` as a "more conventional" word separator. –  Mar 25 '13 at 21:24
6

This will work for you

$('#secondli').remove();
Praveen Dabral
  • 2,261
  • 4
  • 28
  • 42
0

$('#ulId #secondli').remove();

Select the container #ulId and then the list item #secondli. You had forgotten to add the ID tag before the second li.

Zach Shallbetter
  • 1,761
  • 5
  • 22
  • 37
0

You need to add a space between the select the li element,

$('#second li').remove(); // when referencing by id

or

$(".second li").remove(); // when referencing by class
pingle60
  • 500
  • 5
  • 9
0

if you want remove an <li> with ID try :

$('#yourlist #yourli').remove();

otherwise, if you would remove an <li> based on the content you can use :

$('#yourlist li:contains("TextToRemove")').remove();