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?
If you get the element then find its parent then remove the element. from the parent as follows:
It is necessary to go through the parent so this is unavoidable.
Try
$('#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:
It is also possible to target and remove only a single element (Demo) by simply doing:
Be careful with your IDs -- they must match exactly.
attrib04 != attrib4
This will make the
li
elements invisible:Disclaimer: they will still be in the DOM
To remove elements from the DOM use JQuery's
.remove()
method:http://api.jquery.com/remove/