Removing li elements from ul

爱⌒轻易说出口 提交于 2019-12-05 00:30:32

问题


Is it possible using JavaScript to dynamically remove just a few li elements from a ul, given the id's of the li elements?

UPDATE about the actual issue:

I've the following list.

<ul id="attributes" data-role="listview">
    <li id="attrib01">Attribute1</li>
    <li id="attrib02">Attribute2</li>
    <li id="attrib03">Attribute3</li>
    <li id="attrib04">Attribute4</li>
    <li id="attrib05">Attribute5</li>
</ul>

After a ajax request/response, if a particular attribute is "undefined", I want to remove it from the list.

if(typeof data.attrib1 === "undefined")
    $("#attrib01").remove();

I've made sure I'm receiving the correct ajax response. So, the problem now is, that when I remove attrib4, attrib[1-3] are being removed as well. Any idea why this might be happening?


回答1:


Try

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



回答2:


If you get the element then find its parent then remove the element. from the parent as follows:

element = document.getElementById("element-id");
element.parentNode.removeChild(element);

It is necessary to go through the parent so this is unavoidable.




回答3:


$('#id').remove() is the correct way to remove a single element. Note that element IDs must be unique in html, and that invocation must be wrapped in a DOM ready function.

This is a working example based on your html. It loops through all the list-items and removes the one whose id is not present in the data object:

var data = {
    attrib01: "Number 1",
    attrib02: "Number 2",
    attrib04: "Number 4"
};

$(document).ready(function() {
    $("ul > li").each(function() {
        alert(this.id in data); //check if value is defined
        if(!(this.id in data)) {
            $(this).remove();
            // This also works:
            //$('#'+this.id).remove();
        }            
    });
});​

It is also possible to target and remove only a single element (Demo) by simply doing:

$(document).ready(function() {
    $("#attrib04").remove();
});​

Be careful with your IDs -- they must match exactly. attrib04 != attrib4




回答4:


This will make the li elements invisible:

document.getElementById("id_here").style.visibility = "hidden";

Disclaimer: they will still be in the DOM

To remove elements from the DOM use JQuery's .remove() method:

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

http://api.jquery.com/remove/



来源:https://stackoverflow.com/questions/11751111/removing-li-elements-from-ul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!