简体   繁体   English

从ul jQuery中删除li

[英]Remove li from ul jQuery

I have a list with id's that may contain spaces. 我有一个ID可能包含空格的列表。 I have used two approaches to remove an li(by id) from ul : 我使用了两种方法从ul中删除li(按id):

 var element = document.getElementById(<name_of_id>);
 $(element).remove();

 var element = document.getElementById(<name_of_id>);
 element.parentNode.removeChild(element);

Neither of them works! 他们都不行! Please help 请帮忙

Here is my html : 这是我的html:

 <li value='A 1' id='A 1'></li>

Identifier with space are invalid in HTML. 带空格的标识符在HTML中无效。 I would recommend you use valid identifiers. 我建议您使用有效的标识符。

However as you need them you can use Attribute Equals Selector [name=”value”] 但是,根据需要,您可以使用属性等于选择器[name =” value”]

$('[id="ID of element"]').remove(); 

 $('[id="remove this li"]').remove() 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>one</li> <li id="remove this li">two</li> <li>three</li> </ul> 

For HTML 4: 对于HTML 4:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods ("."). ID和NAME令牌必须以字母([A-Za-z])开头,后跟任意数量的字母,数字([0-9]),连字符(“-”),下划线(“ _”) ,冒号(“:”)和句点(“。”)。

For HTML 5: 对于HTML 5:

An id must contain at least one character and may not contain any space characters. ID必须至少包含一个字符,并且不得包含任何空格字符。

Firstly, you should clear that spaces. 首先,您应该清除这些空格。 And then, you can use it: 然后,您可以使用它:

$("#YourElementId").remove();

Id with spaces is invalid except that you can use this to remove the li:- 带空格的ID无效,除了您可以使用它删除li:-

var node = document.getElementById('id');
node.parentNode.removeChild(node);

I have found the answer . 我找到了答案。 Since my id's are being passed into a function, so they are contained in variables. 由于我的ID正在传递到函数中,因此它们包含在变量中。 This is how it works : 这是这样的:

   vmTemplateName = "'"+vmTemplateName+"'"; //id name
   $("[id="+vmTemplateName+"]").remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM